Question

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

Was it helpful?

Solution

  date('Z');

returns the UTC offset in seconds.

OTHER TIPS

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

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

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.

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

This is same JavaScript date.getTimezoneOffset() function:

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

date("Z") will return the UTC offset relative to the server timezone not the user's machine timezone. To get the user's machine timezone you could use the javascript getTimezoneOffset() function which returns the time difference between UTC time and local time, in minutes.

<script type="text/javascript">
    d = new Date();
    window.location.href = "page.php?offset=" + d.getTimezoneOffset();
</script>

And in page.php which holds your php code, you can do whatever you want with that offset value. Or instead of redirecting to another page, you can send the offset value to your php script through Ajax, according to your needs.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top