萬盛學電腦網

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

PHP 日期時間處理:取得本月、上月、下月首尾日期的最佳實踐

為什麼不建議手動運算月份?

手動 $month - 1 處理跨年(1 月 → 12 月)與月份天數差異(28/29/30/31)極易出錯。PHP 內建 DateTime、DateTimeImmutable 與 DateInterval 已完美解決曆法邊界,配合 modify() 相對格式,程式碼更簡潔、可讀、無 Bug。

現代化實作:DateTimeImmutable 鏈式操作

<?php
/**
 * 取得指定月份的首日與末日(含時區支援)
 * @param string|DateTimeInterface|null $reference 參考日期,預設今天
 * @param DateTimeZone|string|null $tz 時區
 * @return array ['start' => DateTimeImmutable, 'end' => DateTimeImmutable]
 */
function getMonthRange($reference = null, $tz = null): array
{
    $dt = $reference instanceof DateTimeInterface
        ? DateTimeImmutable::createFromInterface($reference)
        : new DateTimeImmutable($reference ?? 'today', $tz ? new DateTimeZone($tz) : null);

    // 月首日 00:00:00
    $start = $dt->modify('first day of this month')->setTime(0, 0, 0);
    // 月末日 23:59:59
    $end = $dt->modify('last day of this month')->setTime(23, 59, 59);

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

/** 取得上個月範圍 */
function getLastMonthRange($reference = null, $tz = null): array
{
    $dt = $reference instanceof DateTimeInterface
        ? DateTimeImmutable::createFromInterface($reference)
        : new DateTimeImmutable($reference ?? 'today', $tz ? new DateTimeZone($tz) : null);

    $start = $dt->modify('first day of last month')->setTime(0, 0, 0);
    $end = $dt->modify('last day of last month')->setTime(23, 59, 59);

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

/** 取得下個月範圍 */
function getNextMonthRange($reference = null, $tz = null): array
{
    $dt = $reference instanceof DateTimeInterface
        ? DateTimeImmutable::createFromInterface($reference)
        : new DateTimeImmutable($reference ?? 'today', $tz ? new DateTimeZone($tz) : null);

    $start = $dt->modify('first day of next month')->setTime(0, 0, 0);
    $end = $dt->modify('last day of next month')->setTime(23, 59, 59);

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

使用範例與輸出格式化

<?php
date_default_timezone_set('Asia/Taipei');

$now = new DateTimeImmutable('2024-01-15 14:30:00');

echo "=== 2024-01-15 基準 ===\n";
foreach (['本月' => getMonthRange($now), '上月' => getLastMonthRange($now), '下月' => getNextMonthRange($now)] as $label => $range) {
    echo "$label: {$range['start']->format('Y-m-d H:i:s')} ~ {$range['end']->format('Y-m-d H:i:s')}\n";
}

/*
輸出:
本月: 2024-01-01 00:00:00 ~ 2024-01-31 23:59:59
上月: 2023-12-01 00:00:00 ~ 2023-12-31 23:59:59
下月: 2024-02-01 00:00:00 ~ 2024-02-29 23:59:59  (閏年自動處理)
*/
?>

相對日期格式速查表

格式字串含義範例結果(基準 2024-01-15)
first day of this month本月 1 號2024-01-01
last day of this month本月最後一天2024-01-31
first day of last month上月 1 號2023-12-01
last day of last month上月最後一天2023-12-31
first day of next month下月 1 號2024-02-01
last day of next month下月最後一天2024-02-29
first day of +2 months兩個月後的 1 號2024-03-01
last day of -3 months三個月前的最後一天2023-10-31

常見查詢場景:SQL WHERE 條件建構

<?php
function buildMonthWhereClause(string $column, $reference = null, $tz = null): array
{
    $range = getMonthRange($reference, $tz);
    $start = $range['start']->format('Y-m-d H:i:s');
    $end = $range['end']->format('Y-m-d H:i:s');

    return [
        "{$column} >= ? AND {$column} <= ?",
        [$start, $end],
    ];
}

// PDO 使用
[$sql, $params] = buildMonthWhereClause('created_at', '2024-01-15');
$stmt = $pdo->prepare("SELECT * FROM orders WHERE $sql");
$stmt->execute($params);
?>

避坑指南

  1. 時區一致性:資料庫、PHP、應用層統一用 UTC 存儲,顯示時轉換用戶時區
  2. 不可變物件:優先用 DateTimeImmutable,避免 modify() 副作用污染原變數
  3. 首尾包含邊界:BETWEEN '2024-01-01 00:00:00' AND '2024-01-31 23:59:59' 含毫秒資料可能漏掉,建議 >= start AND < next_month_start
  4. 閏秒/夏令時間:極少數場景需考慮,金融級系統請用專業時間庫

Carbon / Laravel 使用者的快捷寫法

<?php
use Carbon\CarbonImmutable;

$now = CarbonImmutable::now('Asia/Taipei');
$now->startOfMonth();   // 本月首日 00:00:00
$now->endOfMonth();     // 本月末日 23:59:59
$now->subMonth()->startOfMonth(); // 上月首日
$now->addMonth()->endOfMonth();   // 下月末日
?>

總結

拋棄 strtotime() + date() 的字串拼湊,擁抱 DateTimeImmutable 的物件導向日期運算。first day of / last day of 相對格式完美處理跨年、閏年、長短月,程式碼自文檔化,維護成本極低。

copyright © 萬盛學電腦網 all rights reserved