Like us on Facebook and stand a chance to win pen drives!

How to switch between Timezones in PHP

[caption id="attachment_768" align="alignnone" width="502"]timezone timezone[/caption]

[Extracted from : http://www.mindfiresolutions.com/PHP-function-for-Time-Zone-conversion-56.php]

Convert from GMT to a local timezone

[sourcecode language="php"]
function ConvertGMTToLocalTimezone($gmttime,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

$local_timezone = $timezoneRequired;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);
$diff = (strtotime($local) - strtotime($gmt));

$date = new DateTime($gmttime);
$date->modify("+$diff seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;

}
[/sourcecode]

Convert from local timezone to GMT

[sourcecode language="php"]
function ConvertLocalTimezoneToGMT($gmttime,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();

$local_timezone = $timezoneRequired;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);
$diff = (strtotime($gmt) - strtotime($local));

$date = new DateTime($gmttime);
$date->modify("+$diff seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;
}

[/sourcecode]

Convert from one local timezone to another local timezone


[sourcecode language="php"]
function ConvertOneTimezoneToAnotherTimezone($time,$currentTimezone,$timezoneRequired)
{
$system_timezone = date_default_timezone_get();
$local_timezone = $currentTimezone;
date_default_timezone_set($local_timezone);
$local = date("Y-m-d h:i:s A");

date_default_timezone_set("GMT");
$gmt = date("Y-m-d h:i:s A");

$require_timezone = $timezoneRequired;
date_default_timezone_set($require_timezone);
$required = date("Y-m-d h:i:s A");

date_default_timezone_set($system_timezone);

$diff1 = (strtotime($gmt) - strtotime($local));
$diff2 = (strtotime($required) - strtotime($gmt));

$date = new DateTime($time);
$date->modify("+$diff1 seconds");
$date->modify("+$diff2 seconds");
$timestamp = $date->format("Y-m-d h:i:s A");
return $timestamp;
}
[/sourcecode]
[sourcecode language="php"]
echo ConvertGMTToLocalTimezone("2013-03-16 14:28:00","Asia/Seoul")."
";
echo ConvertLocalTimezoneToGMT("2013-03-16 14:28:00","Asia/Seoul")."
";
echo ConvertOneTimezoneToAnotherTimezone("2013-03-16 14:28:00","Asia/Seoul","Australia/South");
[/sourcecode]


1 comment:

  1. echo ConvertOneTimezoneToAnotherTimezone('2014-02-03 04:06:39','America/Phoenix','Asia/Calcutta');

    error

    ReplyDelete

Copyright © 2012 The Code Junction.