Current Location: Home> Latest Articles> Use a loop to traverse all sunset times of the year and generate a chart

Use a loop to traverse all sunset times of the year and generate a chart

M66 2025-05-31

In this article, we will learn how to use PHP's date_sunset function to calculate the sunset time of the year every day and finally generate a graph for visual display. The entire process includes two parts: data collection and chart drawing.

1. Introduction to date_sunset function

PHP's built-in date_sunset function can return the time of sunset based on the specified date, geographical location (latitude and longitude), and altitude. The basic syntax of the function is as follows:

 date_sunset(
    int $timestamp,
    int $returnFormat = SUNFUNCS_RET_STRING,
    ?float $latitude = null,
    ?float $longitude = null,
    ?float $zenith = null,
    ?float $utcOffset = null
): string|int|float|false

Common parameters description:

  • $timestamp : Unix timestamp for date.

  • $returnFormat : The returned format, such as string, timestamp, etc.

  • $latitude and $longitude : geographic coordinates.

  • $utcOffset : Time zone offset (for example, China is 8.0 ).

2. Go through the whole year and collect sunset times

The following PHP code will traverse the whole year in units of every day, obtain the sunset time of each day, and store it in an array:

 <?php
$latitude = 39.9042;  // Example:Beijing&#39;s latitude
$longitude = 116.4074; // Example:Longitude in Beijing
$timezoneOffset = 8.0; // Beijing time

$start = strtotime('2025-01-01');
$end = strtotime('2025-12-31');

$sunsetTimes = [];

for ($day = $start; $day <= $end; $day = strtotime('+1 day', $day)) {
    $sunset = date_sunset($day, SUNFUNCS_RET_STRING, $latitude, $longitude, 90.833333, $timezoneOffset);
    $formattedDate = date('Y-m-d', $day);
    $sunsetTimes[] = [
        'date' => $formattedDate,
        'sunset' => $sunset
    ];
}

// Save toJSONdocument,Convenient front-end drawing
file_put_contents('sunset_data.json', json_encode($sunsetTimes, JSON_PRETTY_PRINT));
?>

After this code is executed, a sunset_data.json file will be generated, which is the sunset time of the day.

3. Use charts to show sunset time

We can use simple front-end libraries such as Chart.js to draw charts. Here is a sample HTML file:

 <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>2025Year sunset time chart</title>
    <script src="https://cdn.jsdelivr.net/npm/chart.js"></script>
</head>
<body>
    <canvas id="sunsetChart" width="1000" height="500"></canvas>

    <script>
        fetch('https://m66.net/sunset_data.json')
            .then(response => response.json())
            .then(data => {
                const labels = data.map(item => item.date);
                const sunsetTimes = data.map(item => {
                    const parts = item.sunset.split(':');
                    return parseInt(parts[0]) + parseInt(parts[1]) / 60;
                });

                const ctx = document.getElementById('sunsetChart').getContext('2d');
                new Chart(ctx, {
                    type: 'line',
                    data: {
                        labels: labels,
                        datasets: [{
                            label: 'Sunset time(Hour)',
                            data: sunsetTimes,
                            borderColor: 'orange',
                            backgroundColor: 'rgba(255,165,0,0.3)',
                            fill: true,
                            tension: 0.3
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                title: {
                                    display: true,
                                    text: 'time(Hour)'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: 'date'
                                },
                                ticks: {
                                    maxTicksLimit: 12
                                }
                            }
                        }
                    }
                });
            });
    </script>
</body>
</html>

Note that the data URL of the above fetch has been replaced with https://m66.net/sunset_data.json , as you request.

4. Summary

Through the above methods, we used PHP to collect sunset data for a whole year and drew a change chart through front-end technology. This allows you to intuitively see the changing trends of sunset time during the year, which is very suitable for weather applications, astronomical observation reminders and other functions.

If you want to make this system more perfect, you can also add caching strategies and support switching between different cities to further improve the user experience.