Rubyist Rubyist - 4 months ago 18
Ruby Question

Easier way to verify a timestamp

I have a program that verifies timestamps, however as of right now it uses a Regex to verify them. What I want to know is if there is an easier way to verify a timestamp in the following format:

05/03/2016 05:34:54 AM
or
PM
.

The methods for the program look like this:

class TimeStampFormatError < StandardError; end

def verify_timestamp(stamp)
begin
if !(stamp[/^\d{1,2}\/\d{1,2}\/\d{4} \d{1,2}:\d{1,2}:\d{1,2} [AP]M\z/])
puts 'Invalid format of timestamp example: 06/07/2016 5:30:23 AM'
raise TimeStampFormatError
else
stamp
end
rescue TimeStampFormatError
puts 'Invalid Timestamp format'
get_timestamp
end
end

def get_timestamp
print 'Enter timestamp: '
tm = gets.chomp
verify_timestamp(tm)
end

Answer

You can use DateTime.strptime with the appropriate format. If it fails with ArgumentError, then the input date string doesn't match the specified format.

require 'date'

begin
  print DateTime.strptime('05/03/2016 05:34:54 AM', '%d/%m/%Y %I:%M:%S %p')
rescue ArgumentError
  print 'not ok'
end

Some testing:

$ ruby -e "require 'date'; begin; print DateTime.strptime('05/03/2016 05:34:54 AM', '%d/%m/%Y %I:%M:%S %p'); rescue ArgumentError; print 'not ok'; end"
2016-03-05T05:34:54+00:00

Another (with a missing M on AM):

$ ruby -e "require 'date'; begin; print DateTime.strptime('05/03/2016 05:34:54 A', '%d/%m/%Y %I:%M:%S %p'); rescue ArgumentError; print 'not ok'; end"
not ok