Ruby 1.87 vs 1.92 Date.parse

In Ruby 1.87 I could do:

Date.parse ("3/21/2011")

Now in 1.9.2 I get:

ArgumentError: invalid date

Any ideas?


Solution 1:

Use strptime and give a specific time format.

ruby-1.9.2-p136 :022 > Date.strptime '03/21/2011', '%m/%d/%Y'
 => #<Date: 2011-03-21 (4911283/2,0,2299161)>

See michaelmichael's response for the reason for this difference between Ruby versions.

Solution 2:

Per this bug report, the ability to parse mm/dd/yy dates was intentionally removed in 1.9. Ruby's creator, Yukihiro Matsumoto says:

"dd/dd/dd" format itself is very culture dependent and ambiguous. It is yy/mm/dd in Japan (and other countries), mm/dd/yy in USA, dd/mm/yy in European countries, right? In some cases, you can tell them by accident, but we should not rely on luck in general cases. I believe that is the reason parsing this format is disabled in 1.9.

As hansengel suggests, you can use Date.strptime instead.

Solution 3:

I have always had difficulty parsing dates with Date.parse. My solution is gratutious of the chronic gem. I also like the strptime function found in another answer.