In Ruby 1.87 I could do:
Date.parse (\"3/21/2011\")
Now in 1.9.2 I get:
<ArgumentError: invalid date
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.
I like the american_date gem for accomplishing this...
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.
class << self
def parse_with_us_format(date, *args)
if date =~ %r{^\d+/\d+/(\d+)$}
Date.strptime date, "%m/%d/#{$1.length == 4 || args.first == false ? '%Y' : '%y'}"
else
parse_without_us_format(date, *args)
end
end
alias_method_chain :parse, :us_format
end
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.