PHP: Determine the Offset between two Time Zones Programming 07 SEP 2009

Because I keep forgetting where I put this code fragment on my system, grabbed from the comments section from the PHP online manual just by the way, I may as well just pop it on here so that I can keep track of it better in the future.

The function you see below is useful for determining the offset (in seconds) between your local (origin) timezone and a remote timezone. In order to run, it requires a remote timezone region string, as well as a second timezone region string if you don’t wish to use the system’s preset timezone. (And if you’re looking for timezone regions strings, may I suggest the excellent as a source?)

So, without further ado, here’s the nifty code:

/**    Returns the offset from the origin timezone to the remote timezone, in seconds.
*    @param $remote_tz;
*    @param $origin_tz; If null the servers current timezone is used as the origin.
*    @return int;

function get_timezone_offset($remote_tz, $origin_tz = null) {
    if($origin_tz === null) {
        if(!is_string($origin_tz = date_default_timezone_get())) {
            return false; // A UTC timestamp was returned -- bail out!
    $origin_dtz = new DateTimeZone($origin_tz);
    $remote_dtz = new DateTimeZone($remote_tz);
    $origin_dt = new DateTime("now", $origin_dtz);
    $remote_dt = new DateTime("now", $remote_dtz);
    $offset = $origin_dtz->getOffset($origin_dt) - $remote_dtz->getOffset($remote_dt);
    return $offset;

And what good would the code be without a nice example to go along with it:

// This will return 10800 (3 hours) ...
$offset = get_timezone_offset('America/Los_Angeles','America/New_York');
// or, if your server time is already set to 'America/New_York'...
$offset = get_timezone_offset('America/Los_Angeles');
// You can then take $offset and adjust your timestamp.
$offset_time = time() + $offset;

It’s clean, it works and I like it, so kudos to the person named Dan at then! :)

wall clocks for different time zones

Related Posts:

About Craig Lotter

Software developer, husband and dad to two little girls. Writer behind An Exploring South African. I don't have time for myself any more.