Rails date format in form field
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.
ActiveSup开发者_JS百科port::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(:default => '%m/%d/%Y')
Thanks
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"
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.
I know this is an awfully old question, but you could use date_field
instead of text_field
. Perhaps that wasn't an option when you asked this question originally.
It displays the date in mm/dd/yyyy
, which is your intent.
<%= date_field :column_name %>
The date_select
form helper provides a "bare bones" date selector.
精彩评论