Incorrect ArgumentError date and incorrect parsing on a valid date?

dates = ["11/12/08 10:47", "11/12/08 13:23", "11/12/08 13:30", "11/25/08 19:21", "2/2/09 11:29", "11/12/08 15:00"] 

This results in an invalid argument error:

 dates.each do |date| d = Date.parse(date) d.mon end #=> ArgumentError: invalid date 

But take your first date at dates , and this is the result:

 d = Date.parse('11/12/08 10:47') puts d.mon #=> #<Date: 2011-12-08 ((2455904j,0s,0n),+0s,2299161j)> #=> 12 but this should be 11 
  • In the first example, why am I getting an invalid ArgumentError?
  • In Example 2, why is the Date object created with mon and day replaced?
+6
source share
2 answers

Given your input, Date.parse parses your dates if they are in YY/MM/DD format, so when it tries to parse 11/25/08 , it fails because the month 25 invalid:

 d = Date.parse('11/12/08 10:47') d.year # => 2011 d.month # => 12 d.day # => 8 Date.parse('11/25/08 19:21') # ArgumentError: invalid date 

Given that your dates are all in one format, you should use Date.strptime :

 d = Date.strptime('11/12/08 10:47', '%m/%d/%y') d.year # => 2008 d.month # => 11 d.day # => 12 Date.strptime('11/25/08 19:21', '%m/%d/%y') # => #<Date: 2008-11-25 ((2454796j,0s,0n),+0s,2299161j)> 

Edit Instead of the format string %m/%d/%y you can use the %D shortcut:

 Date.strptime('11/25/08 19:21', '%D') # => #<Date: 2008-11-25 ((2454796j,0s,0n),+0s,2299161j)> 
+10
source

Ruby Date.parse expects either YYYY-MM-DD (see also ISO8601 for more information) or DD-MM-YYYY but not DD-MM-YY (i.e. 2 digits per year only). The latter is considered instead of YY-MM-DD.

+1
source

All Articles