Parse European Date Formats in Ruby 1.8.6 and 1.8.7

The parse method in Ruby favours US mm-dd-yyyy date formats over European style dd-mm-yyyy formats. Ruby on rails uses the parse method to process Dates from String to Date objects, particularly in form processing. As a result, you need a heavy weight library or some pretty ugly string bashing to parse European formats by default.

Here's code I put together for Ruby 1.8.6 and 1.8.7 that will allow you to parse European dates by default. Throw this code in config/initializers/time_parsing.rb

mDate::Format::EuropeanDates
  def self.included(base)
    base.class_eval do
      class << self
        if RUBY_VERSION == '1.8.6'
          # From here: http://fatvegan.com/2008/05/27/european-dates-in-ruby-on-rails/
          alias_method :_parse_sla_us, :_parse_sla_eu
        else
          # Rewrite Ruby's _parse_sla method.
          def _parse_sla(str, e) # :nodoc:
            if str.sub!(%r|('?-?\d+)/\s*('?\d+)(?:\D\s*('?-?\d+))?|n, ' ') # '
              s3e(e, $3, $2, $1)
              true
            end
          end
        end
      end
    end
  end
end
 
Date.send(:include, Date::Format::EuropeanDate
module Date::Format::EuropeanDates
  def self.included(base)
    base.class_eval do
      class << self
        if RUBY_VERSION == '1.8.6'
          # From here: http://fatvegan.com/2008/05/27/european-dates-in-ruby-on-rails/
          alias_method :_parse_sla_us, :_parse_sla_eu
        else
          # Rewrite Ruby's _parse_sla method.
          def _parse_sla(str, e) # :nodoc:
            if str.sub!(%r|('?-?\d+)/\s*('?\d+)(?:\D\s*('?-?\d+))?|n, ' ') # '
              s3e(e, $3, $2, $1)
              true
            end
          end
        end
      end
    end
  end
end

Date.send(:include, Date::Format::EuropeanDates)