Home > php > PHP find time difference between two countries by country code

PHP find time difference between two countries by country code

To calculate time difference between two countries following code can be used:

i will calculate time difference between United States (New York) and Jamaica

Origin: United States
Destination: Jamaica

Find Jamaica time zone

(note if you need accurate result and/or there are more than 1 timezone in calculated country you need to use city/province code with geoip_time_zone_by_country_and_region() function as second parameter to get timezone)

$timezone = geoip_time_zone_by_country_and_region("JM");

Find offset between destination time zone and origin timezone

$offset = get_timezone_offset($timezone, 'America/New_York');

Our custom get_timezone_offset() function that we use to calculate offset between 2 locations:

function get_timezone_offset($remote_tz, $origin_tz = null) {
    if ($origin_tz === null) {
        if (!is_string($origin_tz = date_default_timezone_get())) {
            return false;
        }
    }
    $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;
}

Add offset to current time:

$offset_time = time() - $offset;

Print current time and timezone of destination country

echo "Time in JM: ".date('Y-m-d H:i', $offset_time) ." ($timezone)</br>";

Convert offset to hour format (default is seconds)

$of=$offset/3600;

Print time difference in hours:

if ($of > 0){
   echo "JM is ".abs($of)." hours behind";
}elseif($of < 0){
   echo "JM is ".abs($of)." hours ahead";
}else{
   echo "There is no time difference";
}

Note:Make sure you set your local time zone at the beginning of you code otherwise time() function results will be in accurate

date_default_timezone_set('America/New_York');

Check out the new version

**get_timezone_offset function is taken from php.net

Advertisements
  1. May 11, 2013 at 12:36 am

    Reblogged this on ITechonology.

  1. No trackbacks yet.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: