Rails Date Parser 1

Posted by Tom Willett Fri, 27 Jun 2008 20:11:00 GMT

I became frustrated with date parsing in Rails and Ruby and so created a user friendly parser for dates. I wanted to avoid a big javascript library or using a date-picker widget. Quite frankly, when I am entering dates, I don't like to have to reach for the mouse and scroll through the dates.

So this is a simple to install simple to use extension to the ruby Date class. To use it simply copy the following code to a file named dateparse.rb and place it in the lib directory in your rails app. Then open up the application controller and and put require 'dateparse' at the top of the file. (Note: put it before the class declaration).

Then in your controller or view code use Date.parse_date() in place of Date.parse(). It recognizes the following formats
    YYYY-mm-dd  ISO Standard
    mm-dd-YYYY  American
    mm-dd      Assume current year
    mm/dd/YYYY American standard
    mm/dd 
    mm.dd.yyyy  European
    dd.mm.yyyy  
    dd mmmmm yyyy example: 22 may 1945 or 22nd may 1945
    dd mmmmm   example: 22 may  (current year)
    mmmm dd yyyy  example: may 22 1945 or may 22nd 1945
    mmmm dd, yyyy  example: may 22, 1945
    mmmm dd     example may 22 or may 22nd
    dd          example  4 or 4th
    today (tod) or now   common names for days and abbreviations
    tomorrow (tom)
    yesterday  (yes)
    Next Week, Last Week, Next Month, Last Month, Next Year, Last Year
    +n[units] or -n[units]: Date from today: examples: '+22', '+22 days',
       '+22d', '-4 weeks', '-4w', '-4week', '+6 months', '+6m', '+6month',  
       '-2 years', '-2y'