lurker
lurker

Reputation: 58324

Anomaly with Ruby Date.parse

I've found a strange behavior in Ruby's Date.parse wondering if someone could shed light on.

Today's date is 17 Oct 2011.

irb(main):027:0> Date.parse("11-20").to_s
=> "2011-10-11"
irb(main):028:0> Date.parse("11/20").to_s
=> "2011-11-20"
irb(main):029:0> Date.parse("1-20").to_s
=> "2011-10-20"
irb(main):032:0> Date.parse("1/20").to_s
=> "2011-01-20"
irb(main):030:0> Date.parse("9-20").to_s
=> "2011-10-20"
irb(main):035:0> Date.parse("9/20").to_s
=> "2011-09-20"
irb(main):031:0> Date.parse("9-10").to_s
=> "2011-10-10"
irb(main):033:0> Date.parse("9/10").to_s
=> "2011-09-10"
irb(main):042:0> Date.parse("1-20-1997").to_s
ArgumentError: invalid date
        from /usr/lib/ruby/1.8/date.rb:956:in `new_by_frags'
        from /usr/lib/ruby/1.8/date.rb:1000:in `parse'
        from (irb):42
        from /usr/lib/ruby/1.8/date.rb:1578
irb(main):043:0> Date.parse("1/20/1997").to_s
=> "1997-01-20"

I'm not sure how it's interpreting the hyphen versus the slash. The slash behavior makes perfect sense to me. But the hyphen behavior is odd. What's parse doing in the hyphen case?

Upvotes: 0

Views: 635

Answers (2)

Antarr Byrd
Antarr Byrd

Reputation: 26169

You may want to look in to using the chronic gem.

Upvotes: 1

Michael Kohl
Michael Kohl

Reputation: 66867

Date.parse internally uses a method called _parse, which you can see here:

http://www.ruby-doc.org/stdlib-1.9.2/libdoc/date/rdoc/Date.html#method-c-_parse

Your last example works if you put the year in front:

Date.parse("1997-1-20") #=> "1997-01-20"

This makes sense if you look at the default argument to Date.parse, which is str='-4712-01-01'. The hyphen form without a year is weird and I personally wouldn't use it.

Upvotes: 3

Related Questions