PHP Calculating Time Difference in Hours Between Two Timezones

Viewed 6628

I need to work out the difference in hours between two timezones and I am running into some issues when the timezone that is ahead moves to the next day.

Example:

//Let's say it is 11pm 23:00 in LA
$local_tz = new DateTimeZone('America/Los_Angeles');
$local = new DateTime('now', $local_tz);
$local_hour = $local->format('H');

//NY is 3 hours ahead, so it is 2am, 02:00
$user_tz = new DateTimeZone('America/New_York');
$user = new DateTime('now', $user_tz);
$user_hour = $user->format('H');

Following the example in this question (Calculate hours between dates in different time zones) I get an incorrect result:

$diff = $user_tz->getOffset($local);
error_log('$diff '.gmdate("H:i:s", $diff)); //outputs 20:00:00

If it was 4pm in LA, therefore 7pm in NY then it is easy:

$time_diff = ($user_h - $local_h); //$time_diff = 3;

But when NY moves to the next day I again get incorrect results:

$time_diff = ($user_h - $local_h); //$time_diff = -21;

So how can I account for another timezone which has moved to a new day?

3 Answers

You can get difference in hours between two time zones using timezone offset try below code:

$local_tz = new DateTimeZone('America/Los_Angeles');
$local = new DateTime('now', $local_tz);

//NY is 3 hours ahead, so it is 2am, 02:00
$user_tz = new DateTimeZone('America/New_York');
$user = new DateTime('now', $user_tz);

$local_offset = $local->getOffset() / 3600;
$user_offset = $user->getOffset() / 3600;

$diff = $user_offset - $local_offset;
print_r($diff); //outputs 3

Function to calculate the difference in hours among two timezones, (input should be in "+00:00" format).

function timezoneDifferenceInHours( $timezone_1, $timezone_2){
    //get hour value of first timezone
    $a = explode(":",$timezone_1)[0];
    //get hour value of second timezone
    $b = explode(":",$timezone_2)[0];
    //calculate difference
    $difference =0;
    if($a < $b)
        $difference = $b-$a;
    else
        $difference = $a-$b;
    return $diffsec;
}

Function call : (returns difference among timezones in hours)

echo timezoneDifferenceInHours( "-07:00", "+05:30" );

//Output : 12
Related