How to retrieve timezone offset from GMT+0 in php?

Jérôme Verstrynge picture Jérôme Verstrynge · Feb 4, 2012 · Viewed 30.1k times · Source

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.

Answer

Teneff picture Teneff · Feb 4, 2012

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);

working example