Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Invalid date ArgumentError and incorrect parse on a valid date?

Tags:

date

ruby

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 throws an invalid argument error:

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

But take the first date in dates and this is the output:

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
  1. In the first example why am I getting an invalid ArgumentError?
  2. In example 2, why is the Date object created with the mon and day swapped?
like image 803
MrPizzaFace Avatar asked May 13 '14 13:05

MrPizzaFace


Video Answer


2 Answers

Given your input, Date.parse is parsing your dates assuming they are in the format YY/MM/DD, so when it try to parse 11/25/08 it fails because 25 is not a valid month:

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 the same format, you should use the Date.strptime method instead:

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 the shortcut %D can be used:

Date.strptime('11/25/08 19:21', '%D')
# => #<Date: 2008-11-25 ((2454796j,0s,0n),+0s,2299161j)>
like image 67
toro2k Avatar answered Sep 20 '22 19:09

toro2k


Ruby's Date.parse is expecting either a YYYY-MM-DD (see also ISO8601 for more information) or a DD-MM-YYYY as well but not DD-MM-YY (i.e. 2 digits only for year). The last is treated instead as YY-MM-DD.

like image 37
Kostas Rousis Avatar answered Sep 22 '22 19:09

Kostas Rousis