Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Calculating Time Difference in Hours Between Two Timezones

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?

like image 538
MP_Webby Avatar asked Sep 18 '17 09:09

MP_Webby


2 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
like image 164
Abutouq Avatar answered Oct 10 '22 17:10

Abutouq


I managed to find a solution to this, the DateInterval class kept throwing out 21 for me aswell, although when I outputted the object I could see the hour as 3.

Since DateTime does the comparison with epoch and ignores timezone, I had to create a new DateTime for both times and THEN run the comparison.

//Let's say it is 11pm 23:00 in LA
$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);

$usersTime = new DateTime($user->format('Y-m-d H:i:s'));
$localsTime = new DateTime($local->format('Y-m-d H:i:s'));

$interval = $usersTime->diff($localsTime);
print_r($interval->h); //outputs 3     

Running tests with $user->modify("-4 hours"); $local->modify("-4 hours"); returns 3. (which puts one of those just before midnight the previous day)

like image 2
IsThisJavascript Avatar answered Oct 10 '22 15:10

IsThisJavascript