Convert 12 hours to 24 hour format in Ruby

How to convert "11am" and "10pm" to "11:00" and "22:00"? Is there an easy way to use date and time classes?

+5
source share
4 answers

First, I would parse the string with Time#strptime, and then print it with Time#strftime. This ensures strict validation with your original format.

require 'time'
Time.strptime("10pm", "%I%P").strftime("%H:%M")
=> "22:00"
+18
source

The time class does not have an analysis method, but DateTime does.

require 'date'
DateTime.parse("11pm").strftime("%H:%M") #=> "23:00"
+11
source

, , "10pm", (1) (2) 24- . . gem install chronic, script :

require 'chronic'
t = Chronic.parse('10pm')
p t.strftime("%H:%M")

"22:00"

+3
source

Do you say that you want 11am and 10pm, and then the opportunity until 11:00 and 22:00, or do you want to show 11:00 and 22:00 instead of 11:00 and 10:00?

if his second question is here:

%H - Hour of the day, 24-hour clock (00 to 23).

#!/usr/bin/ruby -w
time = Time.new

puts time.to_s
puts time.ctime
puts time.localtime
puts time.strftime("%H:%M")

if his first question says:

%I Hour of the day, 12-hour clock (01 to 12).

#!/usr/bin/ruby -w
time = Time.new
timeSwitch = 1

if (timeSwitch == 1)
    puts time.strftime("%H:%M")
else 
    puts time.strftime("%I:%M")
end

Sorry, Perl and Ruby were mixed in syntax

0
source

All Articles