Current Location: Home> Latest Articles> How to Convert the Unix Timestamp Returned by date_sunset() into a Readable Time Format?

How to Convert the Unix Timestamp Returned by date_sunset() into a Readable Time Format?

M66 2025-06-15

In PHP, the date_sunset() function can be used to get the sunset time for a specific location in the form of a Unix timestamp. This function is especially useful when developing weather-related applications or features that adjust page brightness based on geographic location. However, date_sunset() returns a Unix timestamp, which isn't user-friendly, so we need to convert it into a more readable format such as HH:MM:SS or Y-m-d H:i:s.

Below is an example demonstrating how to convert the return value of date_sunset() into a readable time format.

Example Code:

<?php
// Set default timezone
date_default_timezone_set("Asia/Shanghai");
<p>// Get current time<br>
$timestamp = time();</p>
<p>// Specify latitude and longitude (e.g., Beijing)<br>
$latitude = 39.9042;<br>
$longitude = 116.4074;</p>
<p>// Get sunset time (returns Unix timestamp)<br>
$sunsetTimestamp = date_sunset($timestamp, SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude);</p>
<p>// Check if sunset time was successfully retrieved<br>
if ($sunsetTimestamp !== false) {<br>
// Convert to readable format (24-hour)<br>
$readableTime = date("H:i:s", $sunsetTimestamp);<br>
echo "Today's sunset time is: $readableTime";<br>
} else {<br>
echo "Unable to retrieve sunset time.";<br>
}<br>
?><br>

Example Output:

Today's sunset time is: 18:52:34

Tips:

  • The second parameter of date_sunset(), SUNFUNCS_RET_TIMESTAMP, is key—it tells PHP to return a Unix timestamp. You can also use SUNFUNCS_RET_STRING to get a preformatted time string, but manual formatting gives you more customization options.

  • You can use the date() function to format a Unix timestamp into almost any format you want. For example:

date("Y-m-d H:i:s", $sunsetTimestamp);

This will return a complete timestamp like 2025-04-26 18:52:34.

Advanced Use Cases

You can output this time on a webpage, for instance:

echo "<p>Today's sunset time is: $readableTime</p>";

Or use it for dynamic background switching: