7.14. Working with Hours and Minutes Only

We may want to work with times of day as strings. Once again strftime comes to our aid.

We can print the time with hours, minutes, and seconds if we want:

t = Time.now
puts t.strftime("%H:%M:%S")    # Prints 22:07:45

We can print hours and minutes only (and, using the trick of adding 30 seconds to the time, we can even round to the nearest minute):

puts t.strftime("%H:%M")       # Prints 22:07
puts (t+30).strftime("%H:%M")  # Prints 22:08

Finally, if we don’t like the standard 24-hour (or military) clock, we can switch to the 12-hour clock. It’s appropriate to add a meridian indicator then (AM/PM):

puts t.strftime("%I:%M %p")    # Prints 10:07 PM

There are other possibilities, of course. Use your imagination.

Get The Ruby Way: Solutions and Techniques in Ruby Programming, Second Edition now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.