Ruby on rails 如何从Rails时间类获得2位数的小时和分钟

Ruby on rails 如何从Rails时间类获得2位数的小时和分钟,ruby-on-rails,datetime,Ruby On Rails,Datetime,我在看 如何从时间对象中获取两位数的小时和分钟 让我们说我喜欢 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 谢谢使用(%)操作符怎么样?像这样: x = '%02d' % t.hour puts x # prints 07

我在看

如何从时间对象中获取两位数的小时和分钟

让我们说我喜欢

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
谢谢

使用(%)操作符怎么样?像这样:

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

如果你想把你的时间组合成一个可读的字符串或类似的东西,这可能是值得研究的

比如说,

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"
你可以试试这个

Time.now.to_formatted_s(:time)

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

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

要内联设置时区,请执行以下操作:

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

值得一提的是,
to_格式化的
实际上有一个较短的别名
to_格式化的

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