I try to validate an input time in hh:mm
format, so if the user enters time like he:mm:ss
it should throw an error.
My function:
def update_booking_time
# Here need to validate time string
end
I tried with time parse, but I'm not sure how it's working
So how to achieve it?
CodePudding user response:
First, you can use strptime method to create a date object from any format.
require 'time'
time = DateTime.strptime('03-02-2001 04:05:06 PM', '%d-%m-%Y %I:%M:%S %p')#=> #<DateTime: 2001-02-03T16:05:06 00:00 ...>
Then you can use strftime to format according to the directives in the given format string
time.strftime("at %I:%M %p") #=> "at 04:05 PM"
CodePudding user response:
You can use Time.strptime fo this. It takes two arguments, string to parse and expected time format, raising an exception when the string is not correct:
Time.strptime('10:11:15', '%T') #=> 2022-02-21 10:11:15 0000
Time.strptime('25:00:15', '%T') #=> ArgumentError, invalid date or strptime format
(%T
is a shortcut for %H:%M:%S
- more formatting options explained here)