views:

28

answers:

4

I have a text field which is filled with a date from the jQuery UI Datepicker. Depending on the date format the user has selected in their profile on my site, datepicker will either fill in the text field with DD-MM-YYYY or MM-DD-YYYY. If the date is filled in as DD-MM-YYYY, Ruby on Rails interprets this correctly and the date is stored correctly. But when it's MM-DD-YYYY, Ruby on Rails still thinks that it's DD-MM-YYYY and so the date is stored incorrectly. How can I change the date format that Rails is expecting?

A: 

You could send a parameter with your date (i.e. :reverse => true) so that in the controller you can reverse the numbers, if needed, before the date is parsed by Rails.

monocle
+1  A: 

You can use Date.strptime to use any format you want:

>> RUBY_DESCRIPTION
=> "ruby 1.8.7 (2009-06-12 patchlevel 174) [universal-darwin10.0]"

>> require 'date'
=> true

>> Date.strptime('03/04/2010', '%d/%m/%Y').strftime('%c')
=> "Sat Apr  3 00:00:00 2010"

>> Date.strptime('03/04/2010', '%m/%d/%Y').strftime('%c')
=> "Thu Mar  4 00:00:00 2010"

So the first one is to take the 03 as day of month, while the second one is to take it as month.

動靜能量
A: 

In my humble opinion, you should not use server side code to fix or workaround a view problem. Your server code should only mess with one format, and the view should display it in any way the user wants.

If in two months, you add a new locale for your application, you should only have to change your view, not your server code!

One solution should be to use an hidden field. The hidden field is filled with the format that the server deals with (for example %d/%m/%Y format). The text field used for the date picker should be a simple text_field_tag that will be ignored by Rails.

Use onSelect callback : http://jqueryui.com/demos/datepicker/#event-onSelect

to fill in the hidden field with the good format when the user selects a new date in the datepicker :).

slainer68
A: 

May be it will help.

a = "10-30-2010".split('-')
a[0],a[1] = a[1],a[0]
a = a.join('-')
krunal shah