Current Location: Home> Latest Articles> date_sunset() and date_diff() calculate the difference between sunset and current time

date_sunset() and date_diff() calculate the difference between sunset and current time

M66 2025-06-05

In PHP, date_sunset() is a function used to get the sunset time for a specific date and geographic location, while date_diff() can calculate the time interval between two dates and times. Combining these two functions, we can easily draw "how long will it be before sunset today."

Below we use a simple example to demonstrate how to implement this function.

Sample code:

 <?php
// Set the time zone
date_default_timezone_set('Asia/Shanghai');

// Get the current time
$currentTime = new DateTime();

// Set date and geographic location(Take Beijing time and Beijing location as examples)
$timestamp = time();
$latitude = 39.9042;   // Beijing Latitude
$longitude = 116.4074; // Beijing Longitude

// Get the sunset time today(The return is a timestamp)
$sunsetTimestamp = date_sunset(
    $timestamp,
    SUNFUNCS_RET_TIMESTAMP,
    $latitude,
    $longitude,
    90,  // Altitude angle,Generally set as90Indicates standard sunset
    date("Z") / 3600  // The number of hours in the current time zone
);

// Convert sunset time to DateTime Object
$sunsetTime = new DateTime();
$sunsetTime->setTimestamp($sunsetTimestamp);

// Calculate the gap between current time and sunset time
$interval = date_diff($currentTime, $sunsetTime);

// Determine whether there is still time or whether it has sunset
if ($sunsetTime > $currentTime) {
    echo "There is still sunset " . $interval->h . " Hour " . $interval->i . " minute。";
} else {
    echo "The sunset has passed " . $interval->h . " Hour " . $interval->i . " minute。";
}
?>

Output example:

 There is still sunset 2 Hour 34 minute。

Or if it's already sunset:

 The sunset has passed 1 Hour 12 minute。

Notes:

  1. date_sunset() needs to provide latitude and longitude parameters, and the values ​​in different regions will affect the calculation results;

  2. date("Z") / 3600 in the function is used to dynamically obtain the time zone offset of the current server to ensure the accurate results;

  3. date_diff() returns a DateInterval object, where the h and i properties represent the hour and minute parts.