萬盛學電腦網

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

PHP 計算指定日期所屬週的起始與結束日期

前言

報表統計、排程排程、週期性帳單常需「本週一至週日」或「本週日至週六」的日期範圍。PHP DateTime 類別配合 modify() 可輕鬆計算,本文提供可直接使用的函數與物件導向封裝。

函數式實作

<?php
/**
 * 取得指定日期所屬週的起始與結束日期
 *
 * @param string|DateTime $date 目標日期
 * @param int $weekStart 週起始日:1=週一(ISO), 0=週日
 * @return array ['start' => DateTime, 'end' => DateTime]
 */
function getWeekRange($date, int $weekStart = 1): array {
    $dt = $date instanceof DateTime ? clone $date : new DateTime($date);
    $currentDow = (int)$dt->format('w'); // 0=週日 .. 6=週六

    // 計算往前推幾天到週起始日
    $diff = ($currentDow - $weekStart + 7) % 7;
    $start = clone $dt;
    $start->modify("-$diff days")->setTime(0, 0, 0);

    $end = clone $start;
    $end->modify('+6 days')->setTime(23, 59, 59);

    return ['start' => $start, 'end' => $end];
}

// 使用範例
$range = getWeekRange('2024-03-15', 1); // 週一起算
echo "週起始:" . $range['start']->format('Y-m-d') . "\n"; // 2024-03-11
echo "週結束:" . $range['end']->format('Y-m-d') . "\n";   // 2024-03-17

$rangeSun = getWeekRange('2024-03-15', 0); // 週日起算
echo "週起始(週日):" . $rangeSun['start']->format('Y-m-d'); // 2024-03-10

物件導向封裝:WeekRange 類別

class WeekRange {
    public DateTime $start;
    public DateTime $end;
    private int $weekStart;

    public function __construct(DateTime $date, int $weekStart = 1) {
        $this->weekStart = $weekStart;
        $currentDow = (int)$date->format('w');
        $diff = ($currentDow - $weekStart + 7) % 7;

        $this->start = clone $date;
        $this->start->modify("-$diff days")->setTime(0, 0, 0);

        $this->end = clone $this->start;
        $this->end->modify('+6 days')->setTime(23, 59, 59);
    }

    public function contains(DateTime $date): bool {
        return $date >= $this->start && $date <= $this->end;
    }

    public function getDays(): array {
        $days = [];
        $current = clone $this->start;
        while ($current <= $this->end) {
            $days[] = clone $current;
            $current->modify('+1 day');
        }
        return $days;
    }

    public function __toString(): string {
        return $this->start->format('Y-m-d') . ' ~ ' . $this->end->format('Y-m-d');
    }
}

// 使用
$week = new WeekRange(new DateTime('2024-03-15'));
echo $week; // 2024-03-11 ~ 2024-03-17
foreach ($week->getDays() as $day) {
    echo $day->format('D Y-m-d') . "\n";
}

常見陷阱與解決

問題原因解決
跨年週計算錯誤12/31 可能屬於下一年的第 1 週 (ISO-8601)使用 $dt->format('o-W') 取得 ISO 年份與週數
時區導致日期偏移DateTime 預設使用伺服器時區明確設定 date_default_timezone_set 或傳入 DateTimeZone
修改原始 DateTime 物件modify() 會修改原物件必須 clone 後再操作

ISO-8601 週數標準

ISO 規定:週一為週起始,每年第一週包含該年第一個週四。PHP 內建支援:

$dt = new DateTime('2024-12-30');
echo $dt->format('o-\WW'); // 2025-W01 (屬於 2025 年第 1 週)
echo $dt->format('Y-\WW'); // 2024-W01 (錯誤!年份未用 ISO 年)

總結

掌握 DateTime::modify 的相對日期語法("monday this week"、"sunday next week")與 ISO-8601 格式化字元(o、W),即可輕鬆處理各種週期性日期計算需求。

copyright © 萬盛學電腦網 all rights reserved