UTC Offset in PHP

2019-02-01 18:07发布

问题:

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

回答1:

  date('Z');

returns the UTC offset in seconds.



回答2:

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


回答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



回答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.



回答5:

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


回答6:

This is same JavaScript date.getTimezoneOffset() function:

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


回答7:

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.



标签: php timezone utc