當前位置: 首頁> 最新文章列表> 如何使用date_sunset() 獲取格林威治時間(GMT)下的日落時間

如何使用date_sunset() 獲取格林威治時間(GMT)下的日落時間

M66 2025-06-03

在PHP 中, date_sunset()是一個非常實用的函數,它可以用來根據指定的日期、地理位置和其他參數計算太陽的日落時間。本文將介紹如何使用該函數獲取**格林威治時間(GMT)**下的日落時間,並舉例說明其具體用法。

函數簡介

date_sunset(
    int $timestamp,
    int $format = SUNFUNCS_RET_STRING,
    ?float $latitude = ini_get("date.default_latitude"),
    ?float $longitude = ini_get("date.default_longitude"),
    float $zenith = ini_get("date.sunset_zenith"),
    float $gmt_offset = ini_get("date.default_timezone") // PHP 8.1+ 中已移除
): string|int|float|false

但在實際使用中,常見的調用方式更簡單,尤其是在PHP 8.0 及以下版本中。

獲取GMT 下的日落時間

格林威治時間(GMT)對應的是經度0 ,我們可以選取緯度為51.4769 (即英國格林威治天文台附近)作為示例。關鍵點在於將gmt_offset設置為0 ,這樣返回的時間就是GMT 時間。

示例代碼

<?php
// 設置當前時間戳為今天的 12:00 PM
$timestamp = strtotime('today noon');

// 格林威治位置
$latitude = 51.4769;
$longitude = 0.0005;

// 使用 date_sunset 獲取 GMT 下的日落時間(返回時間為字符串格式)
$sunset = date_sunset(
    $timestamp,
    SUNFUNCS_RET_STRING,
    $latitude,
    $longitude,
    90, // zenith 預設值,一般使用 90
    0   // GMT 偏移為 0
);

echo "格林威治時間下的日落時間为: $sunset";
?>

輸出示例(視當前日期而定):

 格林威治時間下的日落時間为: 19:58

注意事項

  1. PHP 8.1+ 的變更:從PHP 8.1 開始, gmt_offset參數已被移除,因此無法直接指定GMT 偏移。如果你使用的是PHP 8.1 或更高版本,建議通過設置默認時區為UTC來實現。

  2. 推薦做法(PHP 8.1+)

 <?php
date_default_timezone_set('UTC');

$timestamp = strtotime('today noon');

$latitude = 51.4769;
$longitude = 0.0005;

$sunset = date_sunset(
    $timestamp,
    SUNFUNCS_RET_STRING,
    $latitude,
    $longitude,
    90
);

echo "格林威治時間(UTC)下的日落時間为: $sunset";
?>
  1. 結果格式:你可以使用SUNFUNCS_RET_TIMESTAMP獲取Unix 時間戳,或使用SUNFUNCS_RET_DOUBLE獲取浮點格式(小時數,例如19.58)。

小結

通過date_sunset()函數,你可以輕鬆地獲取任意地理位置在指定日期下的日落時間。如果你希望獲取的是格林威治時間(GMT),關鍵在於設置經緯度為格林威治天文台附近的坐標,並將時區偏移設置為0(或設置默認時區為UTC)