How would I go about converting a timezone name ["Asia/Dubai", "Europe/Andorra", etc] to a GMT offset in hours [or even seconds, since I can convert it from there].
Most people ask for the reverse, but I need to get a timezone offset from the timezone name provided by GeoNames.
asked Jan 18, 2011 at 19:49
3
you can use the following
answered Jan 18, 2011 at 19:58
Cecil ZorgCecil Zorg
1,45913 silver badges15 bronze badges
3
Another option would be to use the available DateTimeZone::getOffset[]
method, which returns the offset in seconds for the time zone at the specified date/time.
$timezone = new DateTimeZone["Europe/Andorra"];
$offset = $timezone->getOffset[new DateTime];
answered Jan 18, 2011 at 22:33
salathesalathe
50.4k11 gold badges103 silver badges130 bronze badges
1
I like using PHP Carbon:
$offset = Carbon::now['Europe/Andorra']->offsetHours;
answered Jun 5, 2015 at 2:29
mopo922mopo922
6,2063 gold badges27 silver badges31 bronze badges
❮ PHP Date/Time Reference
Example
Return the timezone offset from GMT:
Try it Yourself »
Definition and Usage
The timezone_offset_get[] returns the timezone offset from GMT.
Syntax
timezone_offset_get[object, datetime]
Parameter Values
object | Required. Specifies a DateTimeZone object returned by timezone_open[] |
datetime | Required. Specifies a date/time to compute the offset from |
Technical Details
Returns the timezone offset in seconds on success. FALSE on failure |
5.2+ |
❮ PHP Date/Time Reference
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters. Learn more about bidirectional Unicode characters
/** | |
* Get the offset of the given timezone [in seconds] | |
*/ | |
function getTimeZoneOffset[$timezone=''] { | |
$tz_tmp = new DateTimeZone[$timezone]; | |
$dt_tmp = new DateTime['now', $tz_tmp]; | |
$offset = $dt_tmp->getOffset[]; | |
return $offset; | |
} | |
/** | |
* Convert the given time from the origin time zone to the destination time zone | |
*/ | |
function convertTime[$datetime='0000-00-00 00:00:00', $origin_timezone='GMT', $destination_timezone='GMT', $output_as_mysql=false] { | |
$time = $datetime; | |
if [!is_int[$time]] { | |
$time = strtotime[$datetime]; | |
} | |
$originOffset = $this->getTimeZoneOffset[$origin_timezone]; | |
$destinationOffset = $this->getTimeZoneOffset[$destination_timezone]; | |
$gmtTime = $time - $originOffset; | |
$convertedTime = $gmtTime + $destinationOffset; | |
if [$output_as_mysql] { | |
$convertedTime = date['Y-m-d H:i:s', $convertedTime]; | |
} | |
return $convertedTime; | |
} |