如何从Rails时间等级获得2位数小时和分钟

Abi*_*bid 17 datetime ruby-on-rails

我在看

http://corelib.rubyonrails.org/classes/Time.html#M000245

如何从时间对象获得两位数小时和分钟

让我们说

t = Time.now

t.hour // this returns 7 I want to get 07 instead of just 7
Run Code Online (Sandbox Code Playgroud)

同样的

t.min //  // this returns 3 I want to get 03 instead of just 3
Run Code Online (Sandbox Code Playgroud)

谢谢

Bar*_*aun 29

如果你想把你的时间放在一个可读的字符串或类似的东西,可能值得研究Time#strftime.

例如,

t = Time.now
t.strftime('%H')
  #=> returns a 0-padded string of the hour, like "07"
t.strftime('%M')
  #=> returns a 0-padded string of the minute, like "03"
t.strftime('%H:%M')
  #=> "07:03"
Run Code Online (Sandbox Code Playgroud)


rai*_*7ow 20

如何使用String.format(%)运算符?像这样:

x = '%02d' % t.hour
puts x               # prints 07 if t.hour equals 7
Run Code Online (Sandbox Code Playgroud)


小智 10

你可以试试这个!

Time.now.to_formatted_s(:time)
Run Code Online (Sandbox Code Playgroud)