Search

Chaps

Sweet sweet memories

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

No comments yet.

Leave a comment

Markdown
  • **bold text**
  • *italicized text*
  • > This text is blockquoted
  • * This is an unordered list item
  • 1. This is an ordered list item
  • [Link Text](http://www.example.com/)
  • `code item`

0.055 seconds