views:

310

answers:

2

I've run into a spot of bother with date formats in our Rails application.

I have a date field in our view which I want to be formatted as dd/mm/yy. This is how the user will expect to enter their dates, and the datepicker control uses this format.

However, Active Record seems to be expecting mm/dd/yy.

If I enter 01/03/2010, this gets put in as 03 January 2010.

If I enter 25/03/2010, this gets put in a null.

How do I get ActiveRecord to expect Her Majesties date format?

+1  A: 

Rails' DateTime tries to detect the formatting automatically. It will detect the following formats: mm/dd/yy or dd-mm-yy or yyyy-mm-dd or yyyy/mm/dd. You could monkey-patch DateTime.parse, but I would rather move this issue to the View of your application.

I always recommend to use yyyy-mm-dd [hh:mm:ss] as a string representation for a date. Check the documentation of your DatePicker if it supports multiple date-formats.

The jQuery date-picker for example has this covered with dateFormat (for the data that is sent to the server, set this to yyyy-mm-dd) as well as altFormat (for the input the user sees, set this to dd/mm/yyyy).

Marcel J.
Hmm.. yes I can change the format in the view. I was hoping not to. It surprises me that ActiveRecord can't be localized like this..
Mongus Pong
A: 

Add a file called rails_defaults.rb to config\initializers directory; with following lines:

Date::DATE_FORMATS[:default] = '%d/%m/%Y'
Time::DATE_FORMATS[:default]= '%d/%m/%Y %H:%M:%S'

Restart the server and you are good to go.

KandadaBoggu
I cant get this to work. I have a new_rails_defaults.rb file that was created for me. Putting this in here does not work. Creating the rails_defaults.rb does not work either. Anything else I might have missed?
Mongus Pong
Did you restart your server?
KandadaBoggu
Yes, rebooted the machine just to make sure!
Mongus Pong
Does this rely on a specific rails version? I am on 2.3.4
Mongus Pong
Oh no I'm not... I'm on 2.3.5.
Mongus Pong
My solution will not work as it is. You need to override the to_time, to_date and to_datetime methods on the String class for this to work.
KandadaBoggu