October 2006
Intermediate to advanced
888 pages
16h 55m
English
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:45We 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:08Finally, 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 PMThere are other possibilities, of course. Use your imagination.
Read now
Unlock full access