Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails date format in form field

Tags:

I'd like my dates in the mm/dd/year format in text fields. However, they currently displays as 2010-03-26.

Is there a global setting I can set to change this?

I tried the following, which seems to update the .to_s method, but form fields stay the same.

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y')

Thanks

like image 209
Jack Avatar asked Mar 14 '10 17:03

Jack


2 Answers

You have to register the default format in an initializer.

Add this line to the config/initializers/date_time_formats.rb.

Date::DATE_FORMATS[:default] = '%m/%d/%Y'

# if you want to change the format of Time display then add the line below
Time::DATE_FORMATS[:default]= '%m/%d/%Y %H:%M:%S'

# if you want to change the DB date format.
Time::DATE_FORMATS[:db]= '%m/%d/%Y %H:%M:%S'

Now in the script\console lets test the format.

>> Date.today.to_s
=> "03/14/2010"

>> Time.now.to_s
=> "03/14/2010 13:20:55"
like image 59
Harish Shetty Avatar answered Sep 20 '22 05:09

Harish Shetty


I don't know if there is a global setting for that anywhere, I just do it in the ERB.

<%= text_field_tag("air_date_date", air_date.blank? ? "" : air_date.strftime("%m/%d/%Y"), :class => "date-input text") %>

Alternatively, you can factor this out into a helper function to make it DRY.

like image 33
Randy Simon Avatar answered Sep 18 '22 05:09

Randy Simon