In PHP, date_sunset() is a very practical function that can be used to calculate the sunset time of the sun based on specified dates, geographic locations, and other parameters. This article will introduce how to use this function to obtain the sunset time under Greenwich Time (GMT) and give examples of its specific usage.
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+ Removed
): string|int|float|false
However, in actual use, common calling methods are simpler, especially in PHP 8.0 and below.
Greenwich time (GMT) corresponds to longitude 0 , and we can choose a latitude of 51.4769 (i.e. near the Greenwich Observatory in the UK) as an example. The key point is to set gmt_offset to 0 , so that the returned time is GMT time.
<?php
// Set the current timestamp to today's 12:00 PM
$timestamp = strtotime('today noon');
// Greenwich Location
$latitude = 51.4769;
$longitude = 0.0005;
// use date_sunset Get GMT The sunset time below(Return time in string format)
$sunset = date_sunset(
$timestamp,
SUNFUNCS_RET_STRING,
$latitude,
$longitude,
90, // zenith default value,一般use 90
0 // GMT Offset is 0
);
echo "Greenwich TimeThe sunset time below为: $sunset";
?>
Output example (depending on the current date):
Greenwich TimeThe sunset time below为: 19:58
Changes to PHP 8.1+ : Starting from PHP 8.1, the gmt_offset parameter has been removed, so the GMT offset cannot be specified directly. If you are using PHP 8.1 or later, it is recommended to set the default time zone to UTC .
Recommended practices (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 "Greenwich Time(UTC)The sunset time below为: $sunset";
?>
Result format : You can use SUNFUNCS_RET_TIMESTAMP to get Unix timestamps, or use SUNFUNCS_RET_DOUBLE to get floating point format (hours, for example 19.58).
Through the date_sunset() function, you can easily get the sunset time of any geographical location under a specified date. If you want to get Greenwich Time (GMT), the key is to set the latitude and longitude to the coordinates near the Greenwich Observatory and set the time zone offset to 0 (or set the default time zone to UTC) .