Abid
Abid

Reputation: 7227

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

Upvotes: 22

Views: 46415

Answers (5)

Nathan
Nathan

Reputation: 282

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)

Upvotes: 0

Quv
Quv

Reputation: 3149

For what it's worth, to_formatted_s has actually a shorter alias to_s.

 Time.now.to_s(:time)

Upvotes: 2

Alberto Camargo
Alberto Camargo

Reputation: 149

You can try this!

Time.now.to_formatted_s(:time)

Upvotes: 11

BaronVonBraun
BaronVonBraun

Reputation: 4293

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"

Upvotes: 34

raina77ow
raina77ow

Reputation: 106483

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

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

Upvotes: 22

Related Questions