PHP Conference Japan 2024

DateTimeZone::getOffset

timezone_offset_get

(PHP 5 >= 5.2.0, PHP 7, PHP 8)

DateTimeZone::getOffset -- timezone_offset_get傳回與 GMT 的時區偏移量

說明

物件導向風格

public DateTimeZone::getOffset(DateTimeInterface $datetime): int

程序式風格

此函式會傳回 datetime 參數中指定日期/時間與格林威治標準時間 (GMT) 的偏移量。GMT 偏移量是使用 DateTimeZone 物件中包含的時區資訊計算的。

參數

object

僅限程序式風格:由 timezone_open() 傳回的 DateTimeZone 物件

datetime

包含用於計算偏移量的日期/時間的 DateTime 物件。

傳回值

傳回時區偏移量(以秒為單位)。

範例

範例 #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);

// 使用東京 ($dateTimeZoneJapan) 定義的時區規則計算
// $dateTimeTaipei 物件中包含的日期/時間的 GMT 偏移量。
$timeOffset = $dateTimeZoneJapan->getOffset($dateTimeTaipei);

// 應該顯示 int(32400) (適用於 1951 年 9 月 8 日星期六日本標準時間 01:00:00 之後的日期)。
var_dump($timeOffset);
?>

新增註釋

使用者貢獻的註釋 2 則註釋

Daniel Vidal
2 年前
請注意,DateTime 參數對 DateTimeZone::getOffset($DateTime) 返回的結果沒有影響,除非它指的是一個在參考 DateTimeZone 中有日光節約時間的 DateTime。

例如:
<?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 // 2000 年 6 月沒有日光節約時間
* - 7200 // 巴西在 2020 年之前有日光節約時間
* -10800 // 不再有日光節約時間,所以返回 -10800
*/

?>
匿名
2 年前
整數偏移量不涵蓋像尼泊爾等「特殊」地區的小數偏移量。
To Top