Search code examples
ruby-on-rails-3

How do I change the format ActiveRecord expects when parsing dates from a text field in a form?


The problem

  1. I have a Ruby on Rails model with a Date attribute.
  2. In the form for this model, I am using a single text field with a JQuery datepicker to represent this attribute (not a drop down for each of year, month, and day, as is the Rails custom).
  3. The datepicker inserts dates with a mm/dd/yyyy format.
  4. Rails is expecting dates with a dd/mm/yyyy format.

Examples

  • If a user selects March 12th, 2012, the datepicker puts 03/12/2012, which is interpreted by Rails as December 3rd, 2012.
  • If a user selects March 20th, 2012, the datepicker puts 03/20/2012, which is interpreted by Rails as the 3rd day of the 20th month of 2012. Since this date doesn't exist, Rails casts this to a nil value (I think).

Question

How do I change the date format Rails uses when parsing this date text field?

Notes:

1) I do not want to change the format of the date the datepicker inserts into the text field,

2) I am not asking about displaying my date attribute in a view.


Solution

  • I initially thought this could be solved through the Rails internationalization features, but it turns out I was wrong.

    Ever since Ruby 1.9, the standard format for date parsing is dd/mm/yyyy, so as to better accomodate international users. More details can be found in this SO answer.

    That standard is maintained in Rails, as Date.parse is now used to process data from form inputs. Using a before_validation callback won't work because the field is going to be received as nil by the callback method.

    Right now there are two gems dealing with this specific issue, namely that date parsing in Rails does not follow the locale settings from I18n.locale. Both seem to work well.

    1. delocalize, by clemens - Seems to have been applied successfully in a decent number or projects and has the highest number of stars at the moment.

    2. i18n_alchemy by carlosantoniodasilva - This one has been released more recently. The author is a Rails core team member, and a very active one at that. Definitely deserves a look.