Current Location: Home> Latest Articles> Use date_sunset() to get the sunset time of the specified city

Use date_sunset() to get the sunset time of the specified city

M66 2025-05-31

In PHP, date_sunset() is a very practical function that can help us get the sunset time of a specific city. This function calculates the sunset time of the sun through geographical location (latitude and longitude), and is suitable for scenes where sunset time needs to be dynamically displayed.

1. What is the date_sunset() function?

The date_sunset() function takes some parameters to calculate the sunset time. Its syntax is as follows:

 int date_sunset ( int $timestamp , int $format , float $latitude , float $longitude [, float $zenith [, float $gmt_offset ]] )
  • $timestamp : Specifies the date and timestamp, the default is the current time.

  • $format : The output format, commonly used values ​​are:

    • SUNFUNCS_RET_TIMESTAMP : Returns the Unix timestamp.

    • SUNFUNCS_RET_STRING : Returns a string of date and time.

    • SUNFUNCS_RET_DOUBLE : Returns the number of hours of sunset time (24-hour system).

  • $latitude and $longitude : Specifies the latitude and longitude of the geographical location (in degrees).

  • $zenith : The zenith angle of the sun (default is 90.5, which is the sun's angle at sunset).

  • $gmt_offset : Time zone offset.

2. Sample code: Get the sunset time of a city

Here is a code example that uses date_sunset() to get the sunset time of a city (such as New York):

 <?php
// Set the latitude and longitude of New York
$latitude = 40.7128;  // latitude
$longitude = -74.0060; // longitude

// Get the current timestamp
$timestamp = time();

// Get the sunset time,Format as timestamp
$sunset = date_sunset($timestamp, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude);

// Format sunset time into easy-to-read strings(For example:Y-m-d H:i:s)
echo "The sunset time in New York is:" . date("Y-m-d H:i:s", $sunset);
?>

3. Parsing the code

  • By setting the latitude and longitude of New York ( 40.7128 and -74.0060 ), we can calculate the sunset time in New York.

  • Use the time() function to get the current timestamp and pass it to date_sunset() to get the sunset time of the day.

  • The SUNFUNCS_RET_TIMESTAMP parameter makes the return value a Unix timestamp, and then uses the date() function to format it into a standard date and time format.

4. Use URL to combine date_sunset()

Suppose you want to display this sunset time with the city's relevant information, you can obtain the city's information by calling an API. The following is an example that combines date_sunset() with an external API. In this example, suppose that the API domain name we are visiting is m66.net :