Forwarding Forwarding - 1 month ago 6
Ruby Question

How can I output the AM/PM part of a string received in military time using Ruby?

Say I have a string like 13:00, which is 1:00PM, but only the first two characters (13). How can I output a string datatype of the PM part? Like

'13'.print_ampm()
=> PM

Answer

Use Time#strftime, which is for formatting times. The %p flag will get you an uppercase "AM" or "PM":

t = Time.now
# => 2016-10-14 22:37:03 -0400

t.strftime('%p')
=> "PM"

For just a string that's not a Time object, use:

require 'time'
Time.parse('10:30').strftime('%p')
# => "AM"
Time.parse('23:30').strftime('%p')
# => "PM"

If you want lowercase, use %P instead:

Time.parse('23:30').strftime('%P')
# => "pm"