tags:

views:

58

answers:

3

Hi

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  A: 
/Event \(No \d+\) \d+ at (\d{4})\/(\d{2})\/(\d{2}) (\d\d):(\d\d) \([\w\s]+\)/
Amarghosh
+2  A: 
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.

dhabersack
+5  A: 

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
Lars Haugseth