4

how can i validate that the date and time in the following string is in the right format i.e year, month, day and then the time(4 digits, 2 digits, 2 digits and then the time)

"Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )"

thanks

3 Answers 3

6

Why create your own regular expressions when Ruby can handle the parsing for you?

>> require 'date'
 => true

>> str = "Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )"
>> dt = DateTime.parse(str)
 => #<DateTime: 2010-04-27T11:48:00-08:00 (98212573/40,-1/3,2299161)> 

This also makes sure the date is valid, not just in a recognizable format:

>> str = "Event (No 3) 0007141706 at 2010/13/32 25:61 ( Pacific )"
>> dt = DateTime.parse(str)
ArgumentError: invalid date
Sign up to request clarification or add additional context in comments.

Comments

3
/Event \(No \d+\) \d+ at (\d{4})\/(\d{2})\/(\d{2}) (\d\d):(\d\d) \([\w\s]+\)/

Comments

2
if "Event (No 3) 0007141706 at 2010/04/27 11:48 ( Pacific )" =~ /\d{4}\/\d{2}\/\d{2} \d{2}:\d{2}/
  puts "Date and time found."
end

This will check if your string contains a date and time in the specified format.

It does however only check the amount of digits, so a string containing 2010/13/99 93:71 would be equally valid. Which it is not.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.