Topic: determine if two Dates are a day apart?

hey all,

This seemingly simple problem has a few gotchas. I'm wondering if anyone has tackled this elegantly.

I have avoided using the mday property on Date, just too many edge cases. What if one Date is Oct 31st and the other is Nov 1st for example?

Another issue is daylight's savings. This really threw me for a loop the other day (and broke some things on my site unexpectedly) smile For some reason, the offset on a Date object is dependent on being in daylight's savings.

>> d1 = 2.days.ago.to_date
=> #<Date: 4908343/2,0,2299161>
>> d2 = 3.days.ago.to_date
=> #<Date: 4908341/2,0,2299161>
>> d1.to_time.to_s
=> "Mon Mar 12 00:00:00 -0500 2007"
>> d2.to_time.to_s
=> "Sun Mar 11 00:00:00 -0600 2007"
>> d1.to_time - d2.to_time
=> 82800.0
>> 24 * 60 * 60
=> 86400

As you can see, those two date objects (when convert to Time objects) are not 24 hours apart, but 23.

So this is the method I am using to determine if two dates are a day apart. I make the assumption they are in the same timezone

SECONDS_PER_HOUR = 60 * 60
SECONDS_PER_DAY = 24 * SECONDS_PER_HOUR

def one_day_apart?(date1, date2)
    seconds = date1.to_time - date2.to_time
   
    seconds = seconds.abs
   
    min = SECONDS_PER_DAY - SECONDS_PER_HOUR
    max = SECONDS_PER_DAY + SECONDS_PER_HOUR
   
    return seconds >= min && seconds <= max
end

Re: determine if two Dates are a day apart?

If you are comparing date objects, why does the time play a part in it anyway? Why can't you just do this?

def one_day_apart?(date1, date2)
  (date1 - date2).abs == 1
end

Railscasts - Free Ruby on Rails Screencasts

Re: determine if two Dates are a day apart?

Well, that's why I'm posting smile

I tried just subtracting the date objects first, but wasn't entirely sure what the return value meant (it's a Rational object). But I guess I should have kept in that direction, because you can compare Rationals to Fixnums.

Thanks Ryan!

Re: determine if two Dates are a day apart?

A rational represents a fraction. No clue why subtracting dates returns one because it should always be a whole number anyway. However, it inherits from Numeric and seems to work well with the other numeric classes when it comes to converting and comparing between them.

Railscasts - Free Ruby on Rails Screencasts