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
For that, use Date#strptime . You can use Date#strftime to convert the Date object into preferred format.
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.
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.
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")
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With