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
You can try this!
Time.now.to_formatted_s(:time)
For what it's worth, to_formatted_s
has actually a shorter alias to_s
.
Time.now.to_s(:time)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With