How do I convert \"11am\" and \"10pm\" into \"11:00\" and \"22:00\"? Is there a simple way using the date and time classes?
I would first parse the string with Time#strptime
and then output it with Time#strftime
. This ensures a strict check with your original format as well.
require 'time'
Time.strptime("10pm", "%I%P").strftime("%H:%M")
=> "22:00"
Are you saying you want 11am and 10pm and then the ability to 11:00 and 22:00 or do you want how to show 11:00 and 22:00 instead of 11am and 10pm?
if its the second question 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 its the first question tell:
%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 about that had perl and ruby mixed up on syntax
Your question is unclear, but it sounds like you have a string "10pm", and you need to (1) capture it as a Time, and (2) represent that Time in 24-hour format. I would do it like this. First, gem install chronic
, then, write a script like this:
require 'chronic'
t = Chronic.parse('10pm')
p t.strftime("%H:%M")
Returns "22:00"
The Time class has no parse method, but DateTime has.
require 'date'
DateTime.parse("11pm").strftime("%H:%M") #=> "23:00"