I have a rails form that displays a date in a text_field:
<%= form.text_field :check_in_date %>
The date is rendered as yyyy-m
I added these to my initializers/time_formats.rb
and it works great:
# Default format for displaying dates and times
Date::DATE_FORMATS[:default] = "%m/%d/%Y"
Time::DATE_FORMATS[:default] = "%m/%d/%Y"
Using Ruby 1.9.3 and Rails 3.2.x
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS[:default] = '%m/%d/%Y'
<%= form.text_field :check_in_date, value: model.check_in_date.to_s %>
So I did something like this in the model.
def start_date
super.strftime "%Y/%m/%d %H:%M"
end
Say you have a column called start_date
in model, and want to display another format in the form, just overwrite its value in model.
And nothing needs to be changed in the form.
<%= f.text_field :start_date, class: 'form-control' %>
A slight improvement of Tom Rossis answer is to use the I18n.localize
method, so the default will always be in the current users locale:
initializers/date_time_i18n_formatter.rb
Date::DATE_FORMATS[:default] = ->(date) { I18n.localize date, format: :default }
Time::DATE_FORMATS[:default] = ->(time) { I18n.localize time, format: :default }
Go to your environment.rb file and add the following:
ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(
:default => '%m-%d-%Y' )
Check the official documentation if you feel like reading more :)
This one use location, in your form:
<%= f.text_field :date3, value: ( l @model.date3 if @model.date3? ) %>
In locations en.yml (or es.yml)
en:
date:
formats:
default: "%d/%m/%Y"