Section 7.15. Comparing DateTime Values

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 = 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.

The Ruby Way(c) Solutions and Techniques in Ruby Programming
The Ruby Way, Second Edition: Solutions and Techniques in Ruby Programming (2nd Edition)
ISBN: 0672328844
EAN: 2147483647
Year: 2004
Pages: 269
Authors: Hal Fulton

Similar book on Amazon © 2008-2017.
If you may any questions please contact us: