Topic: determine if two Dates are a day apart?
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) 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>
=> "Mon Mar 12 00:00:00 -0500 2007"
=> "Sun Mar 11 00:00:00 -0600 2007"
>> d1.to_time - d2.to_time
>> 24 * 60 * 60
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