【问题标题】:How to get 2 digit hour and minutes from Rails time class如何从 Rails 时间类中获取 2 位数的小时和分钟
【发布时间】:2012-07-04 03:19:08
【问题描述】:
【问题讨论】:
标签:
ruby-on-rails
datetime
【解决方案1】:
值得一提的是,您可能需要特定时区的小时数。
如果时区已经设置(无论是全局的还是你在一个区块内):
Time.current.to_formatted_s(:time)
内联设置时区:
Time.current.in_time_zone(Location.first.time_zone).to_formatted_s(:time)
【解决方案2】:
不管怎样,to_formatted_s 实际上有一个更短的别名 to_s。
Time.now.to_s(:time)
【解决方案3】:
你可以试试这个!
Time.now.to_formatted_s(:time)
【解决方案4】:
如果你想把你的时间组合成一个可读的字符串或类似的东西,可能值得研究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"
【解决方案5】:
使用String.format (%) 运算符怎么样?像这样:
x = '%02d' % t.hour
puts x # prints 07 if t.hour equals 7