PHP: Difference between timezones

Using PHP, what is the simplest way to get the number of hours and minutes difference between two different time zones?
$tz1 = 'America/Chicago';
$tz1 = 'America/St_Johns';

Open in new window

LVL 10
skijAsked:
Who is Participating?

[Product update] Infrastructure Analysis Tool is now available with Business Accounts.Learn More

x
I wear a lot of hats...

"The solutions and answers provided on Experts Exchange have been extremely helpful to me over the last few years. I wear a lot of hats - Developer, Database Administrator, Help Desk, etc., so I know a lot of things but not a lot about one thing. Experts Exchange gives me answers from people who do know a lot about one thing, in a easy to use platform." -Todd S.

Loganathan NatarajanLAMP DeveloperCommented:
I usually maintain list of time zones in database table and calculate the difference in seconds. Then I use that seconds where ever it requires to calculate.  Check the attachment.

timezone
Julian HansenCommented:
Take a look at the DateTimeZone::getOffset

http://php.net/manual/en/datetimezone.getoffset.php

Sample code
<?php
// Create two timezone objects, one for Chicago and one for St Johns
$dateTimeZoneChicago = new DateTimeZone("America/Chicago");
$dateTimeZoneStJohns = new DateTimeZone("America/St_Johns");

// Create two DateTime objects that will contain the same Unix timestamp, but
// have different timezones attached to them.
$chicago = new DateTime("now", $dateTimeZoneChicago);
$stjohns = new DateTime("now", $dateTimeZoneStJohns);

// Calculate the difference in the times
$diff = (strtotime($chicago->date) - strtotime($stjohns->date)) / 3600;
echo "Diff: {$diff}<br/>";

Open in new window

Working sample here
Ray PaseurCommented:
The procedural way is given in this article.  Using the PHP built-in functions instead of calculating these things yourself is the correct way to go.  Your own calculations are enormously complicated by things like Leap Year, Daylight Savings Time, and similar.  These are "just done and handled" if you use the PHP functions.
http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html

Please see: http://iconoun.com/demo/temp_skij.php
<?php // demo/temp_skij.php

/**
 * http://www.experts-exchange.com/questions/28701866/PHP-Difference-between-timezones.html
 * http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
 */
error_reporting(E_ALL);
echo '<pre>';

// THE VALUE OF TIME IS ALWAYS THE SAME, NO MATTER WHERE YOU ARE ON EARTH
$timestamp = time();

// TIMEZONE SETTINGS ONLY AFFECT THE DISPLAY OF DATE/TIME VALUES
$tz1 = 'America/Chicago';
date_default_timezone_set($tz1);
echo PHP_EOL . date('c', $timestamp);
echo PHP_EOL . date('Z', $timestamp);
$chi = date('Z', $timestamp);

$tz2 = 'America/St_Johns';
date_default_timezone_set($tz2);
echo PHP_EOL . date('c', $timestamp);
echo PHP_EOL . date('Z', $timestamp);
$stj = date('Z', $timestamp);

// COMPUTE THE DIFFERENCE
$dif = $stj - $chi;
echo PHP_EOL . $dif;

// FORMAT THE DIFFERENCE
$fmt = date('H:i', strtotime("TODAY + $dif SECONDS"));
echo PHP_EOL . "$tz2 IS $fmt (HH:MM) AHEAD OF $tz1";

Open in new window

Julian HansenCommented:
Correction to my earlier post
$chicago->date  => date should not be accessed in this manner correct format is $chicago->format(datestring) in which case the difference can be calculated as

$datediff = ($chicago->format('Z') - $stjohns->format('Z')) / 3600;

Open in new window


In comparison to Ray's code I profiled both methods with the following results after 1000 iterations

Ray's code: 0.007606029510498
JH's code: 0.14881801605225

As can be seen from the above Ray's approach is 20x faster.

Therefore recommend points to Ray's post.
Ray PaseurCommented:
Further to Julian's comment, I expect that the difference in execution times is an artifact of object-oriented overhead.  It's the price we pay to write cleaner and leaner code.  In either case, if you need a thousand iterations to use up a fraction of a second, there is likely to be no apparent difference once this is integrated into a web page.

Here is the algorithm packaged in a function that returns an array, and an example of using the function.
<?php // demo/temp_skij.php

/**
 * http://www.experts-exchange.com/questions/28701866/PHP-Difference-between-timezones.html
 * http://www.experts-exchange.com/Web_Development/Web_Languages-Standards/PHP/A_201-Handling-date-and-time-in-PHP-and-MySQL.html
 */
error_reporting(E_ALL);
date_default_timezone_set('America/New_York');
echo '<pre>';

// THE VALUE OF TIME IS ALWAYS THE SAME, NO MATTER WHERE YOU ARE ON EARTH
$timestamp = time();

// TIMEZONE SETTINGS ONLY AFFECT THE DISPLAY OF DATE/TIME VALUES
$tz1 = 'America/Chicago';
date_default_timezone_set($tz1);
echo PHP_EOL . date('c', $timestamp);
echo PHP_EOL . date('Z', $timestamp);
$chi = date('Z', $timestamp);

$tz2 = 'America/St_Johns';
date_default_timezone_set($tz2);
echo PHP_EOL . date('c', $timestamp);
echo PHP_EOL . date('Z', $timestamp);
$stj = date('Z', $timestamp);

// COMPUTE THE DIFFERENCE
$dif = $stj - $chi;
echo PHP_EOL . $dif;

// FORMAT THE DIFFERENCE
$fmt = date('H:i', strtotime("TODAY + $dif SECONDS"));
echo PHP_EOL . "$tz2 IS $fmt (HH:MM) AHEAD OF $tz1";
echo PHP_EOL . "********************" . PHP_EOL;


// PACKAGED AS A FUNCTION
function timezone_difference($tz1, $tz2)
{
    $ret = array
    ( 'from' => $tz1
    , 'is'   => 'same'
    , 'to'   => $tz2
    , 'secs' => '0'
    , 'hhmm' => '00:00'
    )
    ;
    $now = time();
    $sig = NULL;

    // SAVE ORIGINAL TIMEZONE
    $old = date_default_timezone_get();

    // GET TIMEZONE SETTINGS
    date_default_timezone_set($tz1);
    $zz1 = date('Z', $now);

    date_default_timezone_set($tz2);
    $zz2 = date('Z', $now);

    // RESTORE ORIGINAL TIMEZONE
    date_default_timezone_set($old);

    // COMPUTE THE DIFFERENCE
    $dif = $zz2 - $zz1;
    if ($dif < 0) $sig = '-';
    if ($dif > 0) $sig = '+';
    if ($sig == '-') $ret['is'] = 'ahead of';
    if ($sig == '+') $ret['is'] = 'behind';
    $dif = abs($dif);
    $fmt = date('H:i', strtotime("TODAY + $dif SECONDS"));

    // RETURN THE ARRAY
    $ret['secs'] = $sig . $dif;
    $ret['hhmm'] = $sig . $fmt;
    return $ret;
}

// OBSERVE THE FUNCTION
print_r( timezone_difference('America/Chicago', 'America/New_York') );
print_r( timezone_difference('America/New_York', 'America/Chicago') );
print_r( timezone_difference('America/New_York', 'America/New_York') );
print_r( timezone_difference('America/Chicago', 'America/St_Johns') );
print_r( timezone_difference('America/Chicago', 'UTC') );

$tz1 = 'America/Chicago';
$tz2 = 'America/St_Johns';
$t = timezone_difference($tz1, $tz2);
echo PHP_EOL
. 'The clock in '
. $t['from']
. ' is '
. $t['is']
. ' the clock in '
. $t['to']
. '. Convert from the time in '
. $t['from']
. ' to the time in '
. $t['to']
. ' with '
. $t['hhmm']
. ' ('
. $t['secs']
. ' seconds)'
;

$tz2 = 'America/Chicago';
$tz1 = 'America/St_Johns';
$t = timezone_difference($tz1, $tz2);
echo PHP_EOL
. 'The clock in '
. $t['from']
. ' is '
. $t['is']
. ' the clock in '
. $t['to']
. '. Convert from the time in '
. $t['from']
. ' to the time in '
. $t['to']
. ' with '
. $t['hhmm']
. ' ('
. $t['secs']
. ' seconds)'
;

Open in new window

HTH, ~Ray

Experts Exchange Solution brought to you by

Your issues matter to us.

Facing a tech roadblock? Get the help and guidance you need from experienced professionals who care. Ask your question anytime, anywhere, with no hassle.

Start your 7-day free trial
It's more than this solution.Get answers and train to solve all your tech problems - anytime, anywhere.Try it for free Edge Out The Competitionfor your dream job with proven skills and certifications.Get started today Stand Outas the employee with proven skills.Start learning today for free Move Your Career Forwardwith certification training in the latest technologies.Start your trial today
PHP

From novice to tech pro — start learning today.