Forwarding Forwarding - 1 year ago 67
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

=> PM

Answer Source

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

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

=> "PM"

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

require 'time'
# => "AM"
# => "PM"

If you want lowercase, use %P instead:

# => "pm"
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download