萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP 取得指定區間內的日期與月份列表工具函數

日期區間列表產生器:支援逐日、逐月、週顯示

行程表、報表統計、日曆元件常需「給定起迄日期,列出區間內所有日期/月份」。本文提供兩個可直接落地的工具函數,含時間戳驗證、週幾中文顯示、月份跨年處理。

函數一:逐日列表(含週幾)

<?php
/**
 * 取得日期區間內每一天的時間戳、格式化日期、中文週幾
 * @param int $beginTimeStamp 開始時間戳
 * @param int $endTimeStamp   結束時間戳
 * @return array|string 結構化陣列或空字串(參數錯誤)
 */
function timeList(int $beginTimeStamp, int $endTimeStamp): array|string {
    if ($endTimeStamp <= $beginTimeStamp) return '';

    $result = ['timeStampList' => [], 'dayList' => [], 'dayWeek' => []];
    $oneDay = 24 * 3600;

    for ($ts = $beginTimeStamp; $ts <= $endTimeStamp; $ts += $oneDay) {
        $result['timeStampList'][] = $ts;
        $result['dayList'][] = date('Y年m月d日', $ts);
        $result['dayWeek'][] = getChineseWeek($ts);
    }
    return $result;
}

/** 將時間戳轉為中文週幾 */
function getChineseWeek(int $timestamp): string {
    $weekMap = ['周日', '周一', '周二', '周三', '周四', '周五', '周六'];
    return $weekMap[(int)date('w', $timestamp)];
}

// 使用範例
$start = strtotime('2024-01-01');
$end   = strtotime('2024-01-07');
$data = timeList($start, $end);
// $data['dayList']  => ['2024年01月01日', ..., '2024年01月07日']
// $data['dayWeek']  => ['周一', '周二', ..., '周日']
?>

函數二:逐月列表(跨年安全)

<?php
/**
 * 產生從開始月到結束月的所有月份字串 (Y-m)
 * @param int $startTs 開始時間戳
 * @param int $endTs   結束時間戳
 * @return array 月份字串陣列
 */
function monthList(int $startTs, int $endTs): array {
    if ($endTs <= $startTs) return [];

    // 正規化為該月 1 號 00:00:00
    $start = strtotime(date('Y-m-01', $startTs));
    $end   = strtotime(date('Y-m-01', $endTs));

    $months = [];
    while ($start <= $end) {
        $months[] = date('Y-m', $start);
        // 安全加一個月:避免 1/31 +1month 變 3/2 等問題
        $start = strtotime('+1 month', $start);
    }
    return $months;
}

// 使用範例
print_r(monthList(strtotime('2024-01-15'), strtotime('2024-04-10')));
/*
Array
(
    [0] => 2024-01
    [1] => 2024-02
    [2] => 2024-03
    [3] => 2024-04
)
*/
?>

進階應用:產生日曆表格資料結構

function buildCalendar(int $year, int $month): array {
    $firstDayTs = strtotime("{$year}-{$month}-01");
    $daysInMonth = (int)date('t', $firstDayTs);
    $startWeekDay = (int)date('w', $firstDayTs); // 0=Sun

    $weeks = [];
    $week = array_fill(0, 7, null); // 佔位前導空白
    $day = 1;

    // 填入第一週
    for ($i = $startWeekDay; $i < 7 && $day <= $daysInMonth; $i++) {
        $week[$i] = $day++;
    }
    $weeks[] = $week;

    // 後續週
    while ($day <= $daysInMonth) {
        $week = [];
        for ($i = 0; $i < 7 && $day <= $daysInMonth; $i++) {
            $week[] = $day++;
        }
        // 補足週末空白
        while (count($week) < 7) $week[] = null;
        $weeks[] = $week;
    }
    return $weeks;
}

效能提示

  • 大區間(跨年)建議用 DateTime + DatePeriod 物件導向寫法,更優雅且支援時區。
  • 避免在迴圈內重複呼叫 date() 格式化相同時間戳,預先計算好格式字串。
copyright © 萬盛學電腦網 all rights reserved