I have a string: \"31-02-2010\" and want to check whether or not it is a valid date.
What is the best way to do it?
I need a method which which returns
Posting this because it might be of use to someone later. No clue if this is a "good" way to do it or not, but it works for me and is extendible.
class String
def is_date?
temp = self.gsub(/[-.\/]/, '')
['%m%d%Y','%m%d%y','%M%D%Y','%M%D%y'].each do |f|
begin
return true if Date.strptime(temp, f)
rescue
#do nothing
end
end
return false
end
end
This add-on for String class lets you specify your list of delimiters in line 4 and then your list of valid formats in line 5. Not rocket science, but makes it really easy to extend and lets you simply check a string like so:
"test".is_date?
"10-12-2010".is_date?
params[:some_field].is_date?
etc.