Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Ensuring a string is of a time or date format?

Tags:

regex

ruby

I have a method which parses a string in to a date, but i want to validate that i don't try to parse a non numeric string or a string which dosent represent a date or time format?

how can id o this?

at the moment i have:

if(string=~ /^\D*$/ )
{
return false
else 
do something_else
}

this was fine for a non numeric string like "UNKNOWN" but wouldn't work for "UNKNOWN1"

any idea what i can use to make sure that only date or time formats are parsed?

like image 810
Mo. Avatar asked Aug 05 '10 10:08

Mo.


1 Answers

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]
like image 101
Chris McCauley Avatar answered Oct 21 '22 09:10

Chris McCauley