29

I had to debug some tests that just started failing first thing this morning. I guess I should have procrastinated though, because they would have magically fixed themselves tomorrow morning. The cause of the one day only bug: Leap Year Day, of course.

If you run the following code on a day like today, February 29th 2008, Date will choke on your invalid date:

require"date"classDate# Returns a Date in the past +year_offset+ years ago.defself.years_ago(year_offset)now=todayDate.civil(now.year-year_offset,now.month,now.day)endendputsDate.years_ago(1)

I came up with the following fix, which is accurate enough for my purposes:

require"date"classDate# Returns a Date in the past +year_offset+ years ago.defself.years_ago(year_offset)today-365*year_offsetendendputsDate.years_ago(1)

I'm not 100% sure that covers all cases though, so use with caution. Date's are tricky business!

About

James Edward Gray II was a part the Ruby community before Rails
ever shipped. He wrote code and documentation that now come with
the language. He ran two Red Dirt Ruby Conferences and is now
a regular on the Ruby Rogues podcast. He does all of this just
because he loves to program. This site is where he writes about
that.