Thu 19th May 2011 at 00:00

Why is there 5.9583333 days between 24/03/2011 and 30/03/2011

While working on a project recently, I was asked to debug some code to find out why a date difference function was returning some odd results.

function daysdiff($date1, $date2) {
    $daysDiff = ((formatdate('U', $date1 - formatdate('U', $date2))/60/60/24);
    // we increment $daysDiff as we want to count the first day, i.e. same day should be 1, not 0
    $daysDiff++;
    $weeks = floor(($daysDiff+1)/7);
    $days = ($daysDiff+1)-($weeks)*7;

    return ($weeks+$days);
}

 When called daysdiff( '2011-03-24', '2011-03-30') = 5.9583333. The obvious solution was to round the value of $day. OK, the function is crude and a proper solution would be to rewrite the whole function, but that is not really point of this article. What puzzled me is why was the function returning a fraction. After all, the logic looks sound. Each day has 24hours, converting each date into UNIX timestamps and subtracting gives you the number of seconds between, which can then be divided up to give the number of hours. Simple? But yet clearly not. Why had this code managed to be live since December and no one notice. I started trying a few more dates:

  • daysdiff( '2011-03-24', '2011-03-30') = 5.9583333
  • daysdiff( '2011-04-24', '2011-04-30') = 6
  • daysdiff( '2011-01-24', '2011-01-30') = 6
  • daysdiff( '2011-04-01', '2011-04-07') = 6

I started to wonder what was going on in March? And then it struck me! We entered British Summer Time. We lost an hour! To prove the theory I tried the following dates:

  • daysdiff( '2011-03-26', '2011-03-27') = 1
  • daysdiff( '2011-03-27', '2011-03-28') = 0.9583333
  • daysdiff( '2010-03-27', '2011-03-28') = 1
  • daysdiff( '2010-03-28', '2011-03-29') = 0.9583333

 And guess what took place on the 28th March 2010? Yup, the clocks went back.

This site uses cookies, please read my cookie policy.