Difference in dates between servers

131 views Asked by At

I am wondering why I have been getting totally invalid computation by PHP all the time.

I have code like this:

echo floor((strtotime("2017-03-27") - strtotime("2017-03-24"))/86400);

which on the one of the server returns: 3 (like 3 days)

and on the another server returns: 2! (2.9583333333333 day?) Why is there a variance?

3

There are 3 answers

0
junkfoodjunkie On BEST ANSWER

Or, just use better methods:

EDIT I updated the code to use the same dates as OP. It returns 3, as it should, and I'm fairly confident it will do that on whatever server you put it on to test.

<?php

$date1 = date_create('2017-03-27');
$date2 = date_create('2017-03-24');

$interval = date_diff($date1,$date2);

echo $interval->format('%a');

?>

Ref: http://php.net/manual/en/function.date-diff.php

0
Sammitch On

Since some people are having difficulty accepting that this is due to a TZ-specific DST change, have some proof:

function poc($tz_str) {
        $tz = new DateTimeZone($tz_str);
        $start = (new DateTime('2017-03-24', $tz))->format('U');
        $end = (new DateTime('2017-03-27', $tz))->format('U');

        return [$tz_str, $end - $start, ( $end - $start ) / 86400];
}

var_dump(
        poc('UTC'),
        poc('Europe/London'),
        poc('America/New_York')
);

Output:

array(3) {
  [0]=> string(3) "UTC"
  [1]=> int(259200)
  [2]=> int(3)
}
array(3) {
  [0]=> string(13) "Europe/London"
  [1]=> int(255600)
  [2]=> float(2.9583333333333)
}
array(3) {
  [0]=> string(16) "America/New_York"
  [1]=> int(259200)
  [2]=> int(3)
}
  • UTC has no DST, not affected.
  • Most of the eastern hemisphere has their DST change on March 26, affected.
  • Most of the western hemisphere has their DST change on March 12, not affected.

That said, don't do manual date math on a Unix timestamp.

4
user7351608 On

Your servers maybe sitting in two different time zones. Convert the days to hours and you will get a difference of one hour.

3 days        * 24 hours/1 day = 72 hours
2.958333 days * 24 hours/1 day = 71 hours