Search code examples
phpdatedatetimeunix-timestampstrtotime

PHP wrong unix timestamp


find some problem when i was try to count days between two dates.
For fast debug my code i use http://sandbox.onlinephpfunctions.com/ with PHP version 7.4.0

Problem:

$date = new DateTime( '2018-02-28' );
$date2 = new DateTime( '2018-03-12' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
var_dump($diff/(60*60*24)); //float(11.958333333333)

As you see - i set dates and calculated unixtimestamp-diff between dates.
Then i try find date when diff between two dates != 86400.

$date = new DateTime( '2020-03-08' );
$date2 = new DateTime( '2020-03-09' );
$diff = $date2->getTimestamp() - $date->getTimestamp();
var_dump($diff/(60*60*24)); //float(0.95833333333333)

Then i find all days from 2010 year:

$secInDay = 60 * 60 * 24;
$start_date = strtotime('2010-01-01');
$end_date = strtotime('2021-01-01');

while($start_date<$end_date) {
    $next_date = strtotime('+1 day', $start_date);
    $diff = ($next_date - $start_date) / $secInDay;
    if ($diff !== 1) {
        var_dump(date('d.m.Y', $start_date) . ' -> ' . date('d.m.Y', $next_date));
    }
    $start_date = strtotime('+1 day', $start_date);
}

Result:
string(24) "14.03.2010 -> 15.03.2010"
string(24) "07.11.2010 -> 08.11.2010"
string(24) "13.03.2011 -> 14.03.2011"
string(24) "06.11.2011 -> 07.11.2011"
string(24) "11.03.2012 -> 12.03.2012"
string(24) "04.11.2012 -> 05.11.2012"
string(24) "10.03.2013 -> 11.03.2013"
string(24) "03.11.2013 -> 04.11.2013"
string(24) "09.03.2014 -> 10.03.2014"
string(24) "02.11.2014 -> 03.11.2014"
string(24) "08.03.2015 -> 09.03.2015"
string(24) "01.11.2015 -> 02.11.2015"
string(24) "13.03.2016 -> 14.03.2016"
string(24) "06.11.2016 -> 07.11.2016"
string(24) "12.03.2017 -> 13.03.2017"
string(24) "05.11.2017 -> 06.11.2017"
string(24) "11.03.2018 -> 12.03.2018"
string(24) "04.11.2018 -> 05.11.2018"
string(24) "10.03.2019 -> 11.03.2019"
string(24) "03.11.2019 -> 04.11.2019"
string(24) "08.03.2020 -> 09.03.2020"
string(24) "01.11.2020 -> 02.11.2020"

So my main question - why PHP get wrong unix-timestamp for current dates?


Solution

  • Your algorithm finds the days for the changeover from winter/summer time and summer/winter time for the current time zone. These days have not 24 hours.

    Russia no longer knows summer time. With

    date_default_timezone_set('Europe/Moscow');
    

    in the first line you get the result for your region. Try it self.

    Update:

    You get correct results with DateTime-Objects:

    date_default_timezone_set('Europe/Moscow');
    
    $diff = date_create('28.03.2010')->diff(date_create('29.03.2010'))->days;
    echo $diff;  //1