Ensuring a string is of a time or date format?

DateTime.strptime v ParseDate.parsedate

No pun intended but the information herein is now out of date (2015) and some methods and modules have been removed from Ruby 2.x I'm leaving it here just in case someone, somewhere is still using 1.8.7

Ok, maybe there was a small pun intended there ;-)


You would think that you could use either Date.parse or DateTime.parse to check for bad dates (see more on Date.parse here)

d = Date.parse(string) rescue nil

if d 
   do_something
else
   return false
end

because bad values throw an exception which you can catch. However the test strings suggested actually return a Date with Date.parse

For example ..

~\> irb
>> Date.parse '12-UNKN/34/OWN1'
=> #<Date: 4910841/2,0,2299161>
>> 

Date.parse just isn't clever enough to do the job :-(

ParseDate.parsedate does a better job. You can see that it attempts to parse the date but in the test examples, doesn't find a valid year or month. More information here

>> require 'parsedate'
=> true
>> ParseDate.parsedate '2010-09-09'
=> [2010, 9, 9, nil, nil, nil, nil, nil]
>> ParseDate.parsedate 'dsadasd'
=> [nil, nil, nil, nil, nil, nil, nil, nil]
>> ParseDate.parsedate '12-UNKN/34/OWN1'
=> [nil, nil, 12, nil, nil, nil, nil, nil]
>> ParseDate.parsedate '12-UNKN/34/OWN1'
=> [nil, nil, 12, nil, nil, nil, nil, nil]

Tags:

Ruby

Regex