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

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/11315204/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-03 03:38:12  来源:igfitidea点击:

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

ruby-on-railsdatetime

提问by Abid

I am looking at

我在看

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

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

how can I get two digit hour and minutes from a time object

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

Lets say I do

让我说我做

t = Time.now

t.hour // this returns 7 I want to get 07 instead of just 7

same for

同样的

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

Thanks

谢谢

回答by BaronVonBraun

It might be worth looking into Time#strftimeif you're wanting to put your times together into a readable string or something like that.

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

For example,

例如,

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"

回答by raina77ow

How about using String.format(%) operator? Like this:

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

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

回答by Alberto Camargo

You can try this!

你可以试试这个!

Time.now.to_formatted_s(:time)

回答by Nathan Willson

It's worth mentioning that you might want the hours for a specific time zone.

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

If the time zone is already set (either globally or you're in inside a block):

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

Time.current.to_formatted_s(:time)

Time.current.to_formatted_s(:time)

To set the timezone inline:

内联设置时区:

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

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

回答by Quv

For what it's worth, to_formatted_sis actually an alias of to_s.

对于它的价值,to_formatted_s实际上是to_s.

 Time.now.to_s(:time)