Blog Entry

get Ruby 1.9 Date.parse to assume American date format

Ruby 1.9 assumes that everyone has been broken of the bad habit of illogical date formats.

in the console:

1
2
3
4
5
6
7
8
>> 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/american_date_format.rb:

1
2
3
4
5
6
7
8
9
  def Date.parse(value = nil)
    if value =~ /^(\d{1,2})\/(\d{1,2})\/(\d{2})$/
      ::Date.civil($3.to_i + 2000, $1.to_i, $2.to_i)
    elsif value =~ /^(\d{1,2})\/(\d{1,2})\/(\d{4})$/
      ::Date.civil($3.to_i, $1.to_i, $2.to_i)
    else
      ::Date.new(*::Date._parse(value, false).values_at(:year, :mon, :mday))
    end
  end

Now:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
>> 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