hb922
hb922

Reputation: 999

Did I just find a bug in rails Date format?

In trying to parse a date, I have been racking my brain for hours:

Date.today.to_s
=> "06/07/2011" 

Date.today
=> Tue, 07 Jun 2011 

Date.parse Date.today.to_s
 => Wed, 06 Jul 2011 

Date::DATE_FORMATS[:default]
 => "%m/%d/%Y" 

The default format for to_s is different than the default format for parsing? Why would they do this to me?

Using Rails 3.0.5 with Ruby 1.9.2-p180

UPDATE So thanks to your answers, I realize that the DATE_FORMATS is a rails thing while Date.format is using the ruby library (correct?). Is there a way then to parse dates/times with the default DATE_FORMAT without using strptime?

Upvotes: 1

Views: 1138

Answers (3)

Jason
Jason

Reputation: 549

The Chronic gem (link)solves pretty much all date parsing issues (and yes, they can be quite annoying).

Chronic.parse("06/07/2011")
#=> 2011-06-07 12:00:00 +0000

Upvotes: 0

Dylan Markow
Dylan Markow

Reputation: 124479

Normally, Date.today.to_s would return "2011-06-07", but since you set a default date format, it's using "06/07/2011" instead.

Date.parse easily recognizes the YYYY-MM-DD format, but when it sees 06/07/2011 it thinks that's really DD/MM/YYYY (not MM/DD/YYYY as you're expecting -- keep in mind that Date.parse knows nothing about Rails' default date format you set. The default date format is only for Rails' outputting of Date.to_s).

You can force it to parse a MM/DD/YYYY date like this:

Date.strptime(Date.today.to_s, "%m/%d/%Y")
# => Tue, 07 Jun 2011

Upvotes: 5

Devin M
Devin M

Reputation: 9752

I would guess that the to_s method uses a locale option to determine how to write the date.

I dont see how this is an issue though. Date.parse uses heuristics to parse the date so sometimes it will get it wrong.

Upvotes: 0

Related Questions