Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to make US date format as the default when saving to a model in Rails 3

The US date used to be accepted/parsed correctly, but not anymore in Rails 3. The %Y-%m-%d is accepted but not %m/%d/%Y.

g = Grant.new
g.budget_begin_date = '12/31/2010'
#g.budget_begin_date returns nil
g.budget_begin_date = '2010-12-31'
#g.budget_begin_date returns Fri, 31 Dec 2010 00:00:00 UTC +00:00
like image 967
achristoph Avatar asked Oct 28 '10 17:10

achristoph


People also ask

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

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

What is the default format of date?

Date format is MM/DD/CCYY where MM represents a two-digit month, DD represents a two-digit day of the month, CC represents a two-digit century, and YY represents a two-digit year. The date separator may be one of the following characters: '/', '-' or ','. This is the default date format.


2 Answers

As of Ruby 1.9, Date.parse stopped handling the ambiguous format mm/dd/yyyy (american format) or dd/mm/yyyy (rest of civilized world format).

The american_date gem linked here makes the assumption older Ruby did, and can thus parse an american date as expected.

like image 120
Tom Harrison Avatar answered Nov 15 '22 10:11

Tom Harrison


Your code example doesn't quite show Date.parse failing to interpret US style dates, but you're right, it doesn't. Instead of this:

Date.parse("12/31/2010")

Use this:

Date.strptime("12/31/2010", "%m/%d/%Y")
like image 39
dgmdan Avatar answered Nov 15 '22 11:11

dgmdan