當前位置: 首頁> 最新文章列表> 使用循環遍歷一年中所有日落時間並生成圖表

使用循環遍歷一年中所有日落時間並生成圖表

M66 2025-05-31

在本文中,我們將學習如何使用PHP的date_sunset函數,計算一年中每天的日落時間,並最終生成一個圖表進行可視化展示。整個流程包括數據採集和圖表繪製兩個部分。

1. date_sunset函數簡介

PHP內置的date_sunset函數可以根據指定的日期、地理位置(緯度和經度)以及海拔高度,返回日落的時間。函數基本語法如下:

 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

常用參數說明:

  • $timestamp :日期的Unix時間戳。

  • $returnFormat :返回的格式,如字符串、時間戳等。

  • $latitude$longitude :地理坐標。

  • $utcOffset :時區偏移(例如中國是8.0 )。

2. 遍歷一整年並收集日落時間

下面這段PHP代碼將以每天為單位,遍歷一整年,獲取每天的日落時間,並存入數組中:

 <?php
$latitude = 39.9042;  // 示例:北京的緯度
$longitude = 116.4074; // 示例:北京的經度
$timezoneOffset = 8.0; // 北京時間

$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
    ];
}

// 保存到JSON文件,方便前端繪圖
file_put_contents('sunset_data.json', json_encode($sunsetTimes, JSON_PRETTY_PRINT));
?>

這段代碼執行完後,會生成一個sunset_data.json文件,內容是每天的日落時間。

3. 使用圖表展示日落時間

我們可以使用簡單的前端庫(如Chart.js)來繪製圖表。這裡給出一個示例HTML文件:

 <!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <title>2025年日落時間圖表</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: '日落時間(小時)',
                            data: sunsetTimes,
                            borderColor: 'orange',
                            backgroundColor: 'rgba(255,165,0,0.3)',
                            fill: true,
                            tension: 0.3
                        }]
                    },
                    options: {
                        scales: {
                            y: {
                                title: {
                                    display: true,
                                    text: '時間(小時)'
                                }
                            },
                            x: {
                                title: {
                                    display: true,
                                    text: '日期'
                                },
                                ticks: {
                                    maxTicksLimit: 12
                                }
                            }
                        }
                    }
                });
            });
    </script>
</body>
</html>

注意,上面fetch的數據URL已經替換成了https://m66.net/sunset_data.json ,按照你的要求。

4. 小結

通過以上方法,我們用PHP採集了一整年的日落數據,並通過前端技術繪製出了變化圖。這樣可以直觀地看到一年中日落時間的變化趨勢,非常適合做天氣應用、天文觀測提醒等功能。

如果你希望讓這套系統更加完善,還可以加入緩存策略、支持不同城市切換等功能,進一步提升用戶體驗。