skip to Main Content

I’ve a Rails 3.0.7 application that handles many date “text field inputs” in italian format (%d/%m/%Y).

On my Linux Box (configured with italian locale) I run the application and insert into the text box the date 12 november 2014 with an italian format:

12/11/2014 (%d/%m/%Y)

here Rails correctly saves the date without any problem, same thing if I try to insert a date like 27 november 2014:

27/11/2014 (%d/%m/%Y)

On the remote production server the date is wrongly saved swapping day and month parts, so my input:

12/11/2014

is wrongly saved into date:

11/12/2014

and the date input:

27/11/2014

raise an exception because 27 is not a valid month…

I suppose that into production server the problem would be that the date format system setting is wrong (mm/dd/yyyy perhaps…) but the server is administered by a plesk panel and I don’t see anything related to date format system setting…

So the question is: what can I configure in Rails (v. 3.0.x) so that I can save the text field date input in italian format ? (possibly avoiding to write a gazillion of code…)

Many thanks in advance…

2

Answers


  1. Chosen as BEST ANSWER

    Ruby 1.8 uses date format conversion %m/%d/%Y, the 1.9 version instead uses date format %d/%m/%Y, so the solution seems to be switching to Ruby 1.9.x...

    Example, the date 28th december 2015 is parsed:

    In Ruby 1.8: Date.parse("28/01/2015")
    In Ruby 1.9: Date.parse("01/28/2015")
    

  2. Your first step should be setting up the locale:

    # config/initializers/locale.rb
    I18n.default_locale = :it
    

    A few options for dealing with input:

    1. Replace the text inputs with HTML5 date inputs or Javascript "date pickers"

    I really recommend this since you can get validations on the cheap and its a good feature.

    2. Use Time/Date/DateTime .strptime

    params_with_dates = params.merge({
      "date" => Date.strptime( params["date"], '%d/%m/%Y' )
    })
    
    Foo.create(params_with_dates);
    

    Additional reading:

    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search