get Ruby 1.9 Date.parse to assume American date format
By: Johnathon Wright on: March 29, 2011
Ruby 1.9 assumes that everyone has been broken of the bad habit of illogical date formats.
in the console:
Date.parse('2/15/2011') ArgumentError: invalid date
Date.parse('2/15/11') ArgumentError: invalid date
'2/15/2011'.to_date
ArgumentError: invalid date
While I'm driving everyone crazy by writing the date as YYYY-MM-DD, my clients aren't as OCD. They insist on using the American date format mm/dd/yyyy and it's lazy alternate, mm/dd/yy. Here's the code I wrote to help them with their bad habits.
For my rails apps, in config/initializers/americandateformat.rb:
---ruby def Date.parse(value = nil) if value =~ /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/ ::Date.civil($3.toi + 2000, $1.toi, $2.toi) elsif value =~ /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/ ::Date.civil($3.toi, $1.toi, $2.toi) else ::Date.new(*::Date.parse(value, false).valuesat(:year, :mon, :mday)) end
end
Now:
Date.parse('2/15/11') => Tue, 15 Feb 2011
Date.parse('2/15/2011') => Tue, 15 Feb 2011
Date.parse('2011-02-15') => Tue, 15 Feb 2011
'2011-02-15'.to_date => Tue, 15 Feb 2011
'2/4/11'.to_date => Fri, 04 Feb 2011