tags:

views:

1720

answers:

4

I'm trying to calculate the number of days between two days, but I'm running into issues with Daylight Savings Time. Here's my code:

function date_diff($old_date, $new_date) {
    $offset = strtotime($new_date) - strtotime($old_date);
    return $offset/60/60/24;
}

Works fine as long as the days are both within the same DST period:

echo date_diff('3/15/09', '3/18/09'); // 3

But not if they're further apart:

echo date_diff('11/15/08', '3/18/09'); // 122.95833333333

I want an even number of days, and don't care about DST. I suppose I could round the result, but that feels kludgy. Is there a better (easy) way? I don't want to have to write a whole day-parsing-and-counting-avoiding-leap-years thing if I can avoid it.

(Note: this has to run under php 5.1.6, so some of the date features in 5.3 may not be available.)

A bit more info: I'm going to take the offset and add it to other datetimes that are in a db, and I want only the day part to change, not the time part. Turns out rounding won't work, anyway, because when I do the adding it gets off by one hour in the other direction. Maybe there's a better approach to the whole problem....

+3  A: 

you could use http://ca3.php.net/date_default_timezone_set to set the timezone to GMT so there will be no offset.

Alternately, you can manually add an offset using the date('I',$timetamp)

if ( date("I") == 1 ) { // "WE ARE MDT";
$timeZone = "MDT";
} else {
$timeZone = "MST";
}

Eddy
adding this before all my date math seems to be working:date_default_timezone_set('UTC');
sprugman
Using date_default_timezone_set('UTC'); is a great way to do it. Be aware in the case of you needing other dates on your page, it may cause side effects in accuracy of other dates. If you have no other dates on your page, ignore this comment. :-)
artlung
A: 

You can force rounding in a specific direction by using floor() or ceil().

sirlancelot
+2  A: 

Force the dates to live into a timezone without Daylight Savings Time, GMT/UTC:

function date_diff($old_date, $new_date) {
  $offset = strtotime($new_date . " UTC") - strtotime($old_date . " UTC");
  return $offset/60/60/24;
}

echo date_diff('3/15/09', '3/18/09'); // 3
echo date_diff('11/15/08', '3/18/09'); // 123
artlung
A: 

I tried the 'UTC' code above. Didnt work for me. I stll got decimal values.

When there is daylight saving date within the date range the difference serial decimal portion will be either under .5 or over. when date range has day light saving going on 3/15 the decimal value is > .5 when daylight is going off date decimal < .5. so I just put the difference serial in a round() function and I get the whole numbers i need for number of days.

an