jay
jay

Reputation: 1534

Interpreting the output of PHP's DateTimeZone::getOffset function

I am trying use PHP to calculate the number of seconds difference between two time zones. I'm pretty much copying the sample code directly from the PHP documentation at http://www.php.net/manual/en/datetimezone.getoffset.php, but I'm getting the wrong answer (or at least not an intuitively correct answer). My code is:

$my_timezone = new DateTimeZone("America/New_York");
$server_timezone = new DateTimeZone("America/Denver");

$my_date = new DateTime("now", $my_timezone);
$server_date = new DateTime("now", $server_timezone);

var_dump($my_timezone->getOffset($server_date));

The output is int -18000, or -6 hours, but it should be +2 or +3, depending on daylight savings time. Not to mention, the example they give in the PHP documentation shows a seven hour time difference between Taipei and Tokyo, even though they're really one hour apart. Can someone please explain what's going on, and how can I find the correct time difference between two time zones? Thank you very much.

P.S. As long as I'm lost, what's the purpose of the line $my_date = new DateTime("now", $my_timezone);. $my_date is never referenced again in the code.

Upvotes: 0

Views: 662

Answers (1)

Trott
Trott

Reputation: 70183

$my_timezone->getOffset($server_date) returns the offset from GMT of $server_date using the offset rules for $my_timezone. That's why you're getting a result you don't expect.

If you want to get the difference between two time zones using getOffset() you'll have to call getOffset() on both timezones and subtract one from the other.

<?php
$my_timezone = new DateTimeZone("America/New_York");
$server_timezone = new DateTimeZone("America/Denver");

$my_date = new DateTime("now", $my_timezone);
$server_date = new DateTime("now", $server_timezone);

$my_offset = $my_timezone->getOffset($my_date);
$server_offset = $server_timezone->getOffset($server_date);

$diff = $my_offset - $server_offset;    
var_dump($diff);

The above outputs 7200, which is the number of seconds in 2 hours, which is the difference between the time zones.

Upvotes: 2

Related Questions