Friday, February 10, 2012

European dates in ruby 1.9.2

Date parse in Ruby 1.9.2 expects that dates should be in the european format of dd/mm/yyyy. Unfortunately, this meant that my month and days became reversed.

Troyk posted a gist with a solution.

Create an initializer (ruby_date_parse_monkey_patch.rb) with the following:

# Date.parse() with Ruby 1.9 is now defaulting to the European date style where the format is DD/MM/YYYY, not MM/DD/YYYY
# patch it to use US format by default
class Date
  class << self
    alias :euro_parse :_parse
    def _parse(str,comp=false)
      str = str.to_s.strip
      if str == ''
        {}
      elsif str =~ /^(\d{1,2})[-\/](\d{1,2})[-\/](\d{2,4})/
        year,month,day = $3.to_i,$1,$2
        date,*rest = str.split(' ')
        year += (year < 35 ? 2000 : 1900) if year < 100
        euro_parse("#{year}-#{month}-#{day} #{rest.join(' ')}",comp)
      else
        euro_parse(str,comp)
      end  
    end
  end
end

No comments:

Post a Comment