Sep 13

Parsing european date format in Ruby/Rails

UPDATE: new versions of rails use Date._parse instead of ParseDate.parsedate to parse date from string so this would not work. As ParseDate.parsedate have support for DD.MM.YYYY. format in Ruby 1.8.7, parsing would work out of box with.

So you have date in european format DD.MM.YYYY. that you want to parse in ruby? Nothing easier, change parsedate method in ParseDate stdlib.

require ('parsedate')
module ParseDate
  class << self
    alias_method :old_parsedate, :parsedate unless

  def self.parsedate(str)
    match = /(\d{1,2})\.(\d{1,2})\.(\d{2,4})\.?/.match(str)
    return ParseDate.old_parsedate(str) unless match
    [match[3].to_i, match[2].to_i, match[1].to_i, 
     nil, nil, nil, nil, nil] 

On Rails, you can include it in environment.rb file with require ('parsedate_patches.rb').