報表統計常需「最近 12 個月」、「季度回顧」等時間區間列表。本函數輸入基準日期與月數,回傳陣列,每項為 Y-m 格式,正確處理大小月、閏年、跨年邊界。
<?php
/**
* 取得從基準月份起算,向前推算 $months 個月的 Y-m 列表
*
* @param string $baseDate 基準日期 'Y-m-d',預設今天
* @param int $months 需要的月份數,預設 12
* @return array 如 ['2024-01', '2023-12', ...]
*/
function getPreviousMonths(string $baseDate = '', int $months = 12): array {
// 參數驗證
if ($baseDate && !preg_match('/^\d{4}-\d{1,2}-\d{1,2}$/', $baseDate)) {
throw new InvalidArgumentException('日期格式錯誤,應為 Y-m-d');
}
if ($months < 1 || $months > 120) {
throw new InvalidArgumentException('月份數需在 1-120 之間');
}
$result = [];
$timestamp = $baseDate ? strtotime($baseDate) : time();
for ($i = 0; $i < $months; $i++) {
$result[] = date('Y-m', $timestamp);
// 精確推算上個月:先取得當月天數,再減去該天數
$daysInMonth = (int)date('t', $timestamp);
$timestamp = strtotime("-{$daysInMonth} days", $timestamp);
}
return $result;
}
// 使用範例
$list = getPreviousMonths('2024-03-15', 6);
print_r($list);
/*
Array
(
[0] => 2024-03
[1] => 2024-02
[2] => 2024-01
[3] => 2023-12
[4] => 2023-11
[5] => 2023-10
)
*/
strtotime("-{$daysInMonth} days", $timestamp) 精確跳至上個月同一天;若上個月天數較少(如 3/31 → 2/28),PHP 自動調整為該月最後一天。| 錯誤寫法 | 問題 | 正確寫法 |
|---|---|---|
strtotime('-1 month') | 3/31 會變 3/03(PHP 行為),非預期 | 先取得當月天數再減天數 |
mktime(0,0,0, $m-1, $d, $Y) | 需手動處理 $m=1 跨年、$d 超過目標月天數 | 同上,交給 strtotime 內建邏輯 |
BETWEEN 區間:WHERE created_at BETWEEN '2023-10-01' AND '2024-03-31 23:59:59'json_encode($list) 傳給 Chart.js/ECharts。date('Y-m-01') 為基準。日期運算看似簡單,實則暗藏大小月、閏年、時區、夏令時間等陷阱。善用 PHP 內建 DateTime/DateInterval 物件(PHP 5.2+)或 strtotime 相對時間語法,配合嚴格輸入驗證,能寫出健壯且可讀的時間處理程式碼。