Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

like image 759
Abid Avatar asked Jul 03 '12 16:07

Abid


4 Answers

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"
like image 124
BaronVonBraun Avatar answered Nov 01 '22 07:11

BaronVonBraun


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

x = '%02d' % t.hour
puts x               # prints 07 if t.hour equals 7
like image 26
raina77ow Avatar answered Nov 01 '22 08:11

raina77ow


You can try this!

Time.now.to_formatted_s(:time)
like image 11
Alberto Camargo Avatar answered Nov 01 '22 08:11

Alberto Camargo


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

 Time.now.to_s(:time)
like image 2
Quv Avatar answered Nov 01 '22 07:11

Quv