手動 $month - 1 處理跨年(1 月 → 12 月)與月份天數差異(28/29/30/31)極易出錯。PHP 內建 DateTime、DateTimeImmutable 與 DateInterval 已完美解決曆法邊界,配合 modify() 相對格式,程式碼更簡潔、可讀、無 Bug。
<?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 |
<?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);
?>
DateTimeImmutable,避免 modify() 副作用污染原變數BETWEEN '2024-01-01 00:00:00' AND '2024-01-31 23:59:59' 含毫秒資料可能漏掉,建議 >= start AND < next_month_start<?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 相對格式完美處理跨年、閏年、長短月,程式碼自文檔化,維護成本極低。