How to Debug Date.parse

This post is geared towards people using ruby 2.1.5 specifically. If you find your self needing to parse a string into a date object. You know that you have to require the Date class at the head of your ruby file, like so:

1
require 'date'

This will give your current model access, to the Date class and its methods. The next step is always to pass the date string into the parse method, like so:

1
2
date_string = '2/13/1987'
date_obj = Date.parse(date_string)

In ruby 2.1.5 this will give you an error. This error will annoy you, because the error will look like this:

1
2
3
ArgumentError: invalid date
  from (irb):4:in `parse'
  from (irb):4

Clearly it doesnt look like it’s formatted wrong. But unfortunately ruby expects something different, at least in Ruby 2.1.5. The Date class #parse method expects the input to be formatted as (dd/mm/yyyy). If its not formatted that way, you will get an invalid date error. It also looks that strptime also expects the same input. In order to get around this error, you need to switch the date around and then you can use the Date#parse or the Date#strptime methods. Heres one way:

1
2
3
4
date_string = '2/13/1987'
date_string.split('/') # => [2,13,1987]
new_date_string = "#{date_string[1]}/ #{date_string[0]}/ #{date_string[2]}"
date_obj = Date.parse(new_date_string) # => #<Date: 1987-2-13 ((2457056j,0s,0n),+0s,2299161j)>

This is very unexpected behavior, not very friendly for the human programmer, but HEY, what can you do right? Hopefully you’ve stumbled into this post, while your in the middle of your Date.parse hell and I could have helped you get pass the unexpected behavior.