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
Date.valid_date? *date_string.split('-').reverse.map(&:to_i)
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.
Another way to validate date:
date_hash = Date._parse(date.to_s)
Date.valid_date?(date_hash[:year].to_i,
date_hash[:mon].to_i,
date_hash[:mday].to_i)
require 'date'
begin
Date.parse("31-02-2010")
rescue ArgumentError
# handle invalid date
end
I'd like to extend Date
class.
class Date
def self.parsable?(string)
begin
parse(string)
true
rescue ArgumentError
false
end
end
end
Date.parsable?("10-10-2010")
# => true
Date.parse("10-10-2010")
# => Sun, 10 Oct 2010
Date.parsable?("1")
# => false
Date.parse("1")
# ArgumentError: invalid date from (pry):106:in `parse'
Here is a simple one liner:
DateTime.parse date rescue nil
I probably wouldn't recommend doing exactly this in every situation in real life as you force the caller to check for nil, eg. particularly when formatting. If you return a default date|error it may be friendlier.