'UTC Offset in PHP

What's the easiest way to get the UTC offset in PHP, relative to the current (system) timezone?



Solution 1:[1]

  date('Z');

returns the UTC offset in seconds.

Solution 2:[2]

// will output something like +02:00 or -04:00
echo date('P');

Solution 3:[3]

timezone_offset_get()

$this_tz_str = date_default_timezone_get();
$this_tz = new DateTimeZone($this_tz_str);
$now = new DateTime("now", $this_tz);
$offset = $this_tz->getOffset($now);

Untested, but should work

Solution 4:[4]

I did a slightly modified version of what Oscar did.

date_default_timezone_set('America/New_York');
$utc_offset =  date('Z') / 3600;

This gave me the offset from my timezone, EST, to UTC, in hours.

The value of $utc_offset was -4.

Solution 5:[5]

This is same JavaScript date.getTimezoneOffset() function:

<?php
echo date('Z')/-60;
?>

Solution 6:[6]

Simply you can do this:

//Object oriented style
function getUTCOffset_OOP($timezone)
{
    $current   = timezone_open($timezone);
    $utcTime  = new \DateTime('now', new \DateTimeZone('UTC'));
    $offsetInSecs =  $current->getOffset($utcTime);
    $hoursAndSec = gmdate('H:i', abs($offsetInSecs));
    return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}

//Procedural style
function getUTCOffset($timezone)
{
    $current   = timezone_open($timezone);
    $utcTime  = new \DateTime('now', new \DateTimeZone('UTC'));
    $offsetInSecs =  timezone_offset_get( $current, $utcTime);
    $hoursAndSec = gmdate('H:i', abs($offsetInSecs));
    return stripos($offsetInSecs, '-') === false ? "+{$hoursAndSec}" : "-{$hoursAndSec}";
}


$timezone = 'America/Mexico_City';

echo "Procedural style<br>";
echo getUTCOffset($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City
echo "<br>--------------<br>";
echo "Object oriented style<br>";
echo getUTCOffset_OOP($timezone); //-06:00
echo "<br>";
echo "(UTC " . getUTCOffset_OOP($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City

Solution 7:[7]

This will output something formatted as: +0200 or -0400:

echo date('O');

This may be useful for a proper RSS RFC822 format

<pubDate>Sat, 07 Sep 2002 00:00:01 -0500</pubDate>

GMT offsets (like this) shouldn't use a colon (+02:00 from date('P');).

And, although it is acceptable for RSS RFC833, we don't want output like PDT and CST because these are arbitraty and "CST" can mean many things:

Sources

This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.

Source: Stack Overflow

Solution Source
Solution 1 Czimi
Solution 2 Ole V.V.
Solution 3 John Millikin
Solution 4 Kenny
Solution 5
Solution 6
Solution 7 Jesse יִשַׁי