需求:給定任意日期,計算「上個月的今天」。
直觀寫法 strtotime('-1 month') 或 date('Y-m-d', strtotime('-1 month', $time)) 存在嚴重缺陷:
<?php
$time = strtotime('2011-03-31');
echo date('Y-m-d', strtotime('-1 month', $time)); // 輸出 2011-03-03 ❌
// 預期:2011-02-28 (2月只有28天)
原因: PHP 先減月份(3→2),日保持 31,2月無 31 日,自動順延到 3 月 3 日。
<?php
/**
* 計算上個月同一天,若上個月無此日則返回上個月最後一天
* @param int|string $time 時間戳或日期字符串
* @return string 格式 Y-m-d H:i:s
*/
function lastMonthSameDay($time): string {
$ts = is_numeric($time) ? (int)$time : strtotime($time);
// 1. 獲取「上個月第一天 00:00:00」時間戳
// mktime 第 5 參數 day=0 表示「上個月最後一天」
$firstDayLastMonth = mktime(
date('G', $ts), // 時
date('i', $ts), // 分
date('s', $ts), // 秒
date('n', $ts), // 月 (1-12) → 自動處理 1月→12月、年份-1
0, // 關鍵:day=0 表示上個月最後一天
date('Y', $ts) // 年
);
// 2. 獲取上個月總天數
$lastMonthDays = (int)date('t', $firstDayLastMonth); // 't' = 月份天數
// 3. 當前日期
$currentDay = (int)date('j', $ts);
// 4. 判斷上個月是否有「今天」
if ($currentDay > $lastMonthDays) {
// 無此日:返回目標月最後一天,保留原時分秒
return date('Y-m-t H:i:s', $firstDayLastMonth);
} else {
// 有此日:拼接年月+原日期,保留原時分秒
return date('Y-m-' . $currentDay . ' H:i:s', $firstDayLastMonth);
}
}
// 測試用例
$cases = [
'2011-03-31', // 31日 → 2月28日
'2012-03-31', // 閏年 31日 → 2月29日
'2024-01-30', // 30日 → 2023-12-30
'2024-01-31', // 31日 → 2023-12-31
'2024-03-31', // 31日 → 2024-02-29 (閏年)
'2024-05-15', // 普通日期
];
foreach ($cases as $case) {
echo "$case → " . lastMonthSameDay($case) . "\n";
}
/* 輸出:
2011-03-31 → 2011-02-28 00:00:00
2012-03-31 → 2012-02-29 00:00:00
2024-01-30 → 2023-12-30 00:00:00
2024-01-31 → 2023-12-31 00:00:00
2024-03-31 → 2024-02-29 00:00:00
2024-05-15 → 2024-04-15 00:00:00
*/
mktime(..., 0, ...) 神奇用法: `day=0` 表示「上個月最後一天」,`day=-1` 表示「上個月倒數第二天」,以此類推。這是 PHP 日期計算的核心技巧。date('Y-') . date('m', $lastMonth) . '-d' 會在跨年時產生錯誤年份,必須用同一時間戳格式化完整日期部分。<?php
function lastMonthSameDayOO(string $dateStr): string {
$dt = new DateTime($dateStr);
$dt->modify('first day of last month'); // 移動到上個月第一天
$lastDay = (int)$dt->format('t'); // 上個月總天數
$day = (int)$dt->format('j'); // 原日期
if ($day > $lastDay) {
$dt->modify('last day of this month'); // 回到上個月最後一天
} else {
$dt->setDate($dt->format('Y'), $dt->format('m'), $day);
}
return $dt->format('Y-m-d H:i:s');
}
function nextMonthSameDay($time): string {
$ts = is_numeric($time) ? (int)$time : strtotime($time);
// 下個月第一天
$firstDayNextMonth = mktime(
date('G', $ts), date('i', $ts), date('s', $ts),
date('n', $ts) + 1, 1, date('Y', $ts)
);
$nextMonthDays = (int)date('t', $firstDayNextMonth);
$currentDay = (int)date('j', $ts);
if ($currentDay > $nextMonthDays) {
return date('Y-m-t H:i:s', $firstDayNextMonth);
}
return date('Y-m-' . $currentDay . ' H:i:s', $firstDayNextMonth);
}
// PHPUnit 風格測試用例
$tests = [
['2011-03-31', '2011-02-28'],
['2012-03-31', '2012-02-29'],
['2024-01-31', '2023-12-31'],
['2024-02-29', '2024-01-29'], // 閏年 2月29日 → 1月29日
['2024-03-31', '2024-02-29'],
['2023-01-01', '2022-12-01'],
];
foreach ($tests as [$input, $expect]) {
$result = substr(lastMonthSameDay($input), 0, 10);
assert($result === $expect, "Failed: $input => $result, expect $expect");
}
echo "All tests passed.\n";