繁体   English   中英

如何从 Rails 时间类中获取 2 位数的小时和分钟

[英]How to get 2 digit hour and minutes from Rails time class

我在看

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

同样的

t.min //  // this returns 3 I want to get 03 instead of just 3

谢谢

如果你想把你的时间放在一个可读的字符串或类似的东西中,可能值得研究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"

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

x = '%02d' % t.hour
puts x               # prints 07 if t.hour equals 7

你可以试试这个!

Time.now.to_formatted_s(:time)

值得一提的是, to_formatted_s实际上有一个较短的别名to_s

 Time.now.to_s(:time)

值得一提的是,您可能需要特定时区的小时数。

如果时区已经设置(全局或您在块内):

Time.current.to_formatted_s(:time)

内联设置时区:

Time.current.in_time_zone(Location.first.time_zone).to_formatted_s(:time)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM