Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Rails date format in a text_field

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-mm-dd

I'm trying to figure out how to have it display as mm-dd-yyyy

I tried adding this config but it didn't work.

ActiveSupport::CoreExtensions::Date::Conversions::DATE_FORMATS.merge!(   :default => '%m/%d/%Y' ) 
like image 794
Nathan Avatar asked Sep 20 '09 00:09

Nathan


People also ask

How do I change the date format in Ruby on Rails?

You need to convert your string into Date object. For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.


2 Answers

Simple one time solution is to use :value option within text_field call instead of adding something to ActiveRecord::Base or CoreExtensions.

For example:

<%= f.text_field :some_date, value: @model_instance.some_date.strftime("%d-%m-%Y") %> 
like image 188
Kamil Sarna Avatar answered Sep 28 '22 16:09

Kamil Sarna


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

like image 35
Tom Rossi Avatar answered Sep 28 '22 17:09

Tom Rossi