相对于当前(系统)时区,在PHP中获取UTC偏移量的最简单方法是什么?
date('Z');
以秒为单位返回UTC偏移量.
// 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);
未经测试,但应该工作
我对奥斯卡所做的略有修改.
date_default_timezone_set('America/New_York'); $utc_offset = date('Z') / 3600;
这给了我从时区EST到UTC的偏差,以小时为单位.
$ utc_offset的值为-4.
只需执行以下操作即可:
//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
"; echo getUTCOffset($timezone); //-06:00 echo "
"; echo "(UTC " . getUTCOffset($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City echo "
--------------
"; echo "Object oriented style
"; echo getUTCOffset_OOP($timezone); //-06:00 echo "
"; echo "(UTC " . getUTCOffset_OOP($timezone) . ") " . $timezone; // (UTC -06:00) America/Mexico_City