ruby Date.month,前导零

Nat*_*n H 7 ruby datetime

Date在Ruby中有一个对象.

我什么时候myobj.month得到8.如何获得具有前导零的日期月份,例如08.

同样的想法day.

我最终想要得到的是2015/08/05.

knu*_*nut 9

有可能使用格式化的字符串输出

例子:

puts sprintf('%02i', 8)
puts '%02i' % 8
Run Code Online (Sandbox Code Playgroud)

%02i是带有前导零的2位宽度整数(数字)的格式.有关详细信息,请参阅sprintf的文档

在具有日期的特定情况下,您可以使用Time#strftimeod Date#strftime方法:

require 'time'
puts Time.new(2015,8,1).strftime("%m")
Run Code Online (Sandbox Code Playgroud)