简体   繁体   中英

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

I am looking at

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

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

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"

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

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)

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)

To set the timezone inline:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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