Informatika Mihelac
September 13 2006 rails | tips

Parsing european date format in Ruby/Rails

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
        method_defined?(:old_parsedate)
  end

  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] 
  end
end

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

comments feed

6 comments

  1. # On February 02, 2007 at 07:02 AM, Mike McKay said:
    Where do you save the above file? In lib?
  2. # On February 02, 2007 at 08:02 AM, bmihelac said:
    Yes lib folder would be right place to put file.
  3. # On February 16, 2007 at 14:02 PM, Peter said:
    As none of the strategies I found did fully satisfy me, I have now made a plugin that does format the date, selectively for specific attributes, when
    1. pre-filling an input form (from a database entry or some default),
    2. parsing the input form from a POST action
    3. (optionally) presenting it in regular output
    All one has to do is mention the respective attributes in the model, like dt_datum_parse :date_field1, :date_field2, ...
    dt_datum_view :date_field1, :date_field2, ...
    It provides the "german" date (like "28.02.2007") and works with postgresQL - which is what I need. (It does currently not support "datetime" fields and such.) You're welcome to try it out, optimize, enhance it... http://80.237.237.126/download/rails-plugins/dt_datum-1.0.tar.gz PMc
  4. # On May 13, 2007 at 13:05 PM, dimi3 said:
    It's easier to just write a method like: def format_date(value) sprintf value.day.to_s + '.' + value.month.to_s + '.' + value.year.to_s end Or whatever you'd like.
  5. # On April 22, 2008 at 17:04 PM, anton@kopylov.net said:

    “I find much easy way: d = Date.strptime(‘07.02.2008’, ‘%d.%m.%Y’) “

  6. # On June 15, 2008 at 01:06 AM, Elmer Davis said:

    clithridiate diversiform wricht misstater teataster nenuphar photogrammetric protropical Kihei Akahi Rental Unit D607 http://www.wise-info.co.uk

Speak your mind:

(Required)

(Required)


(You may use textile in your comments.)

About

I am Bojan Mihelac and this blog is dedicated to share code, thoughts, tools and advices I came up with while working in Informatika Mihelac.

Contact: bmihelac@mihelac.org

RSS feedSubscribe to RSS Feed