How to retrieve timezone offset from GMT+0 in php?
-
22-04-2021 - |
Question
I am no expert in php. I know timezones are supported in PHP.
For a given timezone TZ supported by PHP, I need to retrieve the offset (i.e., number of hours and minutes to add or substract) to a known UTC (i.e. GMT+0) to get that time in the TZ zone.
How can I achieve this? Ultimately, I need to get those offsets for all supported timezones in PHP. Thanks.
Solution
This is a simple example how to get timezone offset in seconds:
$dtz = new DateTimeZone('Europe/Sofia');
$time_in_sofia = new DateTime('now', $dtz);
echo $dtz->getOffset( $time_in_sofia );
to display it in the format GMT+x:
$offset = $dtz->getOffset( $time_in_sofia ) / 3600;
echo "GMT" . ($offset < 0 ? $offset : "+".$offset);
OTHER TIPS
This will be useful for converting offset values into GMT format without any calculation
<?php
//target time zone
$target_time_zone = new DateTimeZone('America/Los_Angeles');
//find kolkata time
$date_time = new DateTime('now', $target_time_zone);
//get the exact GMT format
echo 'GMT '.$date_time->format('P');
This will get you the standard offset (not the one in or out of DST [depending on the time of year]):
function getStandardOffsetUTC($timezone)
{
if($timezone == 'UTC') {
return '';
} else {
$timezone = new DateTimeZone($timezone);
$transitions = $timezone->getTransitions(time() - 86400*365, time());
foreach ($transitions as $transition)
{
if ($transition['isdst'])
{
continue;
}
return sprintf('UTC %+03d:%02u', $transition['offset'] / 3600, abs($transition['offset']) % 3600 / 60);
}
return false;
}
}
Usage:
echo getStandardOffsetUTC('Europe/Sofia'); // UTC +02:00
You can get a peek at the differences here.
It is possible just by the following single line.
echo (new DateTime('now', new DateTimeZone( 'Asia/Kabul' )))->format('P');
For all supported timezones in PHP:
$timezone_offsets = array();
foreach(timezone_identifiers_list() as $timezone_identifier)
{
$date_time_zone = new DateTimeZone($timezone_identifier);
$date_time = new DateTime('now', $date_time_zone);
$timezone_offsets[$timezone_identifier] = $date_time_zone->getOffset($date_time);
}
print_r($timezone_offsets);