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?
Normally,
Date.today.to_swould return “2011-06-07”, but since you set a default date format, it’s using “06/07/2011” instead.Date.parseeasily 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 thatDate.parseknows nothing about Rails’ default date format you set. The default date format is only for Rails’ outputting ofDate.to_s).You can force it to parse a MM/DD/YYYY date like this: