How to check if a string is a valid date How to check if a string is a valid date ruby ruby

How to check if a string is a valid date


require 'date'begin   Date.parse("31-02-2010")rescue ArgumentError   # handle invalid dateend


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.


d, m, y = date_string.split '-'Date.valid_date? y.to_i, m.to_i, d.to_i