Simon Larsen
Simon Larsen

Reputation: 59

php datetime diff completely off

So i have this very simple code but it refuse to work, and i have no idea why?

$date1= new DateTime (gmdate('H:i Y-m-d'));
$date2 = new DateTime('now', new DateTimeZone('America/New_York'));

echo $date1->format('H:i Y-m-d') .'<br>'; returns //08:32 2018-06-08
echo $date2->format('H:i Y-m-d') .'<br><br>'; returns //04:32 2018-06-08

$diff = $date1->diff($date2);


$diffTime = $diff->format('%R%H:%I');

echo $diffTime; returns //+02:00

I'm no mathematician but i'm pretty sure the difference between 04:32 and 08:32 isn't 2 hours, but more like 4.

And if i change it it sometimes end up being even more off.

    $date1 = new DateTime ('now', new DateTimeZone('Indian/Comoro'));
    $date2 = new DateTime('now', new DateTimeZone('America/New_York'));

    echo $date1->format('H:i Y-m-d') .'<br>'; returns //11:44 2018-06-08
    echo $date2->format('H:i Y-m-d') .'<br><br>'; returns //04:44 2018-06-08


    $diff = $date1->diff($date2);


    $diffTime = $diff->format('%R%H:%I');

    echo $diffTime; returns //+00:00

I just don't even.

Upvotes: 1

Views: 57

Answers (3)

Andreas
Andreas

Reputation: 23958

gmdate shows time without DST, and in New York it's currently DST.

If you use "Europe/London" instead you have DST on both ends.

$date1= new DateTime ('now', new DateTimeZone('Europe/London'));
$date2 = new DateTime('now', new DateTimeZone('America/New_York'));

echo $date1->format('H:i Y-m-d') .'<br>';  
echo $date2->format('H:i Y-m-d') .'<br><br>'; 

$diff = $date1->diff($date2);


$diffTime = $diff->format('%R%H:%I');

echo $diffTime;  //+00:00

https://3v4l.org/b6Gkq

Upvotes: 0

Bhumi Shah
Bhumi Shah

Reputation: 9476

Here is the updated code. It returns -07:00

$date1 = new DateTime ('now', new DateTimeZone('Indian/Comoro'));
    $date2 = new DateTime('now', new DateTimeZone('America/New_York'));

    echo $date1->format('h:i Y-m-d') .'<br>';/// returns //11:44 2018-06-08
    echo $date2->format('h:i Y-m-d') .'<br><br>';// returns //04:44 2018-06-08
    $datetime1 = new DateTime($date1->format('h:i Y-m-d'));
    $datetime2 = new DateTime( $date2->format('h:i Y-m-d'));

    $diff = $datetime1->diff($datetime2);


    $diffTime = $diff->format('%R%H:%I');

    echo $diffTime; returns //-07:00

Upvotes: 1

NitinSingh
NitinSingh

Reputation: 2068

When you request for "now" date object, it returns you the present date. How it formats depends on your client locale, or the one you explicitly specify.

However, when you have two date objects, both on now (maybe formatted as two different timezones), when you do a compare (or diff), they are supposed to return the same value as inherently a date object is the number of ticks since 1/1/1970.

If you want to check, output the "ticks" property of each date, you will see they come out same.

Hence your code is working fine absolutely.

Upvotes: 1

Related Questions