Regex to match mm/dd/yyyy hh:mm:ss AM or PM

后端 未结 5 1304
逝去的感伤
逝去的感伤 2021-01-22 16:57

I have a program that creates information for a time stamp, the time stamp has to match the following format: MM/DD/YYYY HH:MM:SS AM or PM

For example:

5条回答
  •  旧巷少年郎
    2021-01-22 17:35

    I don't think a regex is the right tool for this job. I'd use DateTime.strptime, give it the format you're expecting and let it deal with all the "50 hours is invalid in a time of day", "09 versus 9", ... issues.

    Something like:

    require 'date'
    
    def timestamp
      print 'Enter the time stamp to verify: '
      ts = gets.chomp # You might want to include a String#strip call in here too
      DateTime.strptime(ts, '%m/%d/%Y %I:%M:%S %p')
      puts ts
    rescue ArgumentError
      puts 'Invalid formatting of time stamp'
      exit 1
    end
    

    Regexes are nice but they shouldn't be the only parsing tool you have.

提交回复
热议问题