Search

Friends

Atomspheric CO2 (PPM)

Archives

Blather

Uptime verified by Wormly.com

13 May 2008

Rails autocasting date strings with wrong day month order

Update: I found a better solution that changes the date parsing code instead.

# Overrides the default AR date casting for dates of format dd/mm/yyyy
module ActiveRecord
  module ConnectionAdapters #:nodoc:
    class Column
      def self.fallback_string_to_date(string)
        string.gsub!(/([0-9]{2})\/([0-9]{2})\/([0-9]{4})/, '\3-\2-\1') # Convert to unambiguous date
        new_date *ParseDate.parsedate(string)[0..2]
      end
    end
  end
end

Rails ActiveRecord (or ParseDate at least) assumes that date strings with forward slashes are always in the form mm/dd/yyyy. That's all very well for silly countries like America, but not for a lot of the rest of the world.

This is my fairly shite attempt to transparently solve this problem. If you put this code in lib/autocast_date.rb for instance you can go require 'autocast_date' at the top of any model that needs it.

This will obviously break support for American style dates.

Comments

  1. This worked nicely, thanks.

    Luke / 9:10pm / 17 September 2009

  2. Oh god. I forgot how bad that code was.

    Ryan / 10:20pm / 17 September 2009

Leave a comment

Markdown

0.879 seconds