In PHP, the date_sunset() function returns the sunset time of a specified location, usually in UTC time (coordinated Universal Time). If you want to convert this UTC time to a readable format, the gmdate() function is a great tool that converts UTC time into the format you need.
This article will explain how to format the UTC sunset time returned by date_sunset() into readable time using gmdate() .
First, we need to get the sunset time, and the date_sunset() function will return a UTC timestamp. The following sample code demonstrates how to get the sunset time:
$latitude = 40.730610; // latitude
$longitude = -73.935242; // longitude
// Get the sunset timestamp for the current date(UTC)
$sunset = date_sunset(time(), SUNFUNCS_RET_TIMESTAMP, $latitude, $longitude);
// Print out sunset time stamp
echo "Sunset Time Stamp(UTC):$sunset\n";
Through the gmdate() function, we can convert the returned UTC timestamp to a readable format. The gmdate() function allows you to specify the format and convert the UTC timestamp to the time string you need.
Here is an example of how to convert a sunset timestamp to a readable time using the gmdate() function:
// 格式化Sunset Time Stamp
$formatted_sunset = gmdate("Y-m-d H:i:s", $sunset);
// Print out the formatted time
echo "Formatted sunset time(UTC):$formatted_sunset\n";
In this example, gmdate() returns the sunset time using the Ymd H:i:s format. You can adjust the format of date and time as needed.
If you want to convert UTC time to the local time of your time zone, you can use the DateTime class and use the DateTimeZone to convert the time zone. Here is an example showing how to convert UTC sunset time to Beijing time:
// Create a DateTime Object,Indicates sunset UTC time
$datetime_utc = new DateTime("@$sunset"); // use @ Symbols for representation Unix time戳
$datetime_utc->setTimezone(new DateTimeZone('Asia/Shanghai')); // 转换为北京time
// 格式化并打印本地time
echo "北京time日落time:".$datetime_utc->format("Y-m-d H:i:s")."\n";
Use gmdate() to convert the UTC sunset timestamp returned by date_sunset() into a readable time format. You can also use the DateTime class to convert UTC time to the time in the local time zone. With these simple steps, you can easily get and format the sunset time to make it more friendly and easy to read.