int offset does not cover fractional offsets of "rogue" locations such as Nepal etc.
(PHP 5 >= 5.2.0, PHP 7, PHP 8)
DateTimeZone::getOffset -- timezone_offset_get — 返回相对于 GMT 的时差
面向对象风格
过程化风格
该函数返回参数 datetime
中指定的日期/时间相对于 GMT
的时差。GMT 时差是通过 DateTimeZone 对象的时区信息计算出来的。
成功时返回精确到秒的时差, 或者在失败时返回 false
。
示例 #1 DateTimeZone::getOffset() 例子
<?php
// 创建两个时区对象,分别是台北(台湾)和东京(日本)
$dateTimeZoneTaipei = new DateTimeZone("Asia/Taipei");
$dateTimeZoneJapan = new DateTimeZone("Asia/Tokyo");
// 创建两个包含相同 Unix 时间戳的 DateTime 对象。区别是对应的时区不同。
$dateTimeTaipei = new DateTime("now", $dateTimeZoneTaipei);
$dateTimeJapan = new DateTime("now", $dateTimeZoneJapan);
// 计算包含日期/时间的 $dateTimeTaipei 对象与时区规则定义为东京的 $dateTimeZoneJapan 对象的 GMT 时差
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);
// 应该展示 int(32400)(Sat Sep 8 01:00:00 1951 JST 之后的日期)。
var_dump($timeOffset);
?>
int offset does not cover fractional offsets of "rogue" locations such as Nepal etc.
Note that the DateTime parameter has no effect in the result returned by DateTimeZone::getOffset($DateTime), unless, it refers to a DateTime where there is daylight savings in the referenced DateTimeZone.
Ex.:
<?php
$timezone_brl = new DateTimeZone('America/Sao_Paulo');
$timezone_eng = new DateTimeZone('Europe/London');
$timezone_aus = new DateTimeZone('Australia/Brisbane');
$dateTimes = [
new DateTime()
, new DateTime('now', $timezone_eng)
, new DateTime('now', $timezone_aus)
, new DateTime('now', $timezone_brl)
, new DateTime('2000-06-10', $timezone_brl)
, new DateTime('2000-12-10', $timezone_brl)
, new DateTime('2020-12-10', $timezone_brl)
];
foreach($dateTimes as $dateTime)
{
echo "\n" . $timezone_brl->getOffset($dateTime);
}
/**
* -10800
* -10800
* -10800
* -10800
* -10800 // No daylight savings in June/2000
* - 7200 // Brazil had daylight savings until 2020
* -10800 // No more daylight savings, so it returns -10800
*/
?>