Search code examples
phpdatetimedateinterval

PHP DateTime difference in hours with timezone gives 0 instead of 2


I'm trying to build a list of timezone with the time difference between the php timezone code and UTC.

I've try a few lines of code with diff:

$utc_date = new DateTime(
    NULL,
    new DateTimeZone('UTC')
);
echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A') . "<br>";

$cairo_date = new DateTime(
    NULL,
    new DateTimeZone('Africa/Cairo')
);
echo 'Cairo:  ' . $cairo_date->format('Y-m-d g:i A') . "<br>";

$diff = $utc_date->diff($cairo_date);
echo "Differences: " . $diff->h;

It outputs that:

UTC: 2020-05-17 9:14 PM
Cairo: 2020-05-17 11:14 PM
Differences: 0

I can't find why diff doesn't return the correct differences ?


Solution

  • The diff function you call will return different timestamp. So, there are same moment will return 0. You should call different time zone between them. Exmaple:

    $utc_date = new DateTime(
        NULL,
        new DateTimeZone('UTC')
    );
    echo 'UTC:  ' . $utc_date->format('Y-m-d g:i A') . "<br>";
    
    $cairo_date = new DateTime(
        NULL,
        new DateTimeZone('Africa/Cairo')
    );
    echo 'Cairo:  ' . $cairo_date->format('Y-m-d g:i A') . "<br>";
    
    $cairo_timeZone = timezone_open('Africa/Cairo');
    
    echo "Differences: " . timezone_offset_get($cairo_timeZone, $utc_date)/3600; //hour