Search code examples
rubydateparsinghashargument-error

Ruby Date Gem Invalid Date


So I am iterating through a hash where one of the key/values is {date: => 'MM/DD/YYYY'}

When I iterate through, I am using the date gem to find out what day of the week that each date is, (0-6).

To get a day of the week for the index I am currently at as an integer so i can compare it to another integer, the idea is to check if the day of the week of the index is the same as the day of the week i am searching for.

To get that int I run the following commands:

d = Date.parse(hash[i].values[2])
day_of_the_week = d.cwday

When i do this on its own for just a cherry-picked date this works fine, but I am iterating through the hash, what i get is:

search.rb:25:in `parse': invalid date (ArgumentError)

for the particular date '9/13/17'.

Is there something wrong with '9/13/17'? Why does this actually work for other days (it starts at '9/5/17') and then get randomly stuck at this day?

And as I was writing this, I did a little digging and found exactly what index it was:

d = Date.parse(hash[4224].values[2])
day_of_the_week = d.cwday

Gives me the same error, I am completely baffled, what is going on? Also its not the lack of MM in 9/etc because every other month is the same way.

EDIT: The result should be 2, September 12th 2017 was a Tuesday.


Solution

  • You need to pass the format of your date, use

    Date.strptime('9/13/2017', '%m/%e/%Y').