How to check if a string is a valid date

Salil picture Salil · Jun 2, 2010 · Viewed 88.2k times · Source

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 true if the string is a valid date and false if it is not.

Answer

mpd picture mpd · Jun 2, 2010
require 'date'
begin
   Date.parse("31-02-2010")
rescue ArgumentError
   # handle invalid date
end