PHP strtotime() 支援強大的自然語言相對時間,獲取上月最後一天極其簡單:
date_default_timezone_set('PRC'); // 設置時區
echo date('Y-m-d', strtotime('last day of last month')); // 2024-11-30
echo date('Y-m-d', strtotime('first day of this month -1 day'));
// 利用當前日期倒推
$day = (int)date('d');
echo date('Y-m-d', strtotime("-$day days")); // 有閏年/月末邊界風險
<?php
date_default_timezone_set("PRC");
// 推薦:語義清晰、自動處理閏年/月長差異
$lastDayPrevMonth = date('Y-m-d', strtotime('last day of last month'));
echo "上月最後一天: $lastDayPrevMonth
";
// 獲取上月第一天
$firstDayPrevMonth = date('Y-m-d', strtotime('first day of last month'));
echo "上月第一天: $firstDayPrevMonth
";
// 獲取上月天數
$daysInPrevMonth = date('t', strtotime('last month'));
echo "上月天數: $daysInPrevMonth
";
// 格式化輸出
echo "上月範圍: $firstDayPrevMonth 至 $lastDayPrevMonth";
| 表達式 | 含義 | 示例輸出 |
|---|---|---|
| last day of last month | 上月最後一天 | 2024-11-30 |
| first day of last month | 上月第一天 | 2024-11-01 |
| last day of this month | 本月最後一天 | 2024-12-31 |
| first day of this month | 本月第一天 | 2024-12-01 |
| last day of +2 months | 兩個月後最後一天 | 2025-02-28 |
| last day of -1 month | 上月最後一天(同義) | 2024-11-30 |
date_default_timezone_set('PRC') 或 php.ini date.timezone,否則用 UTC 導致日期偏移$dt = new DateTime('last day of last month', new DateTimeZone('PRC'));
echo $dt->format('Y-m-d'); // 2024-11-30
// 區間迭代
$start = new DateTime('first day of last month');
$end = new DateTime('last day of last month');
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach ($period as $day) {
echo $day->format('Y-m-d') . "\n";
}
首選 strtotime('last day of last month'):語義明確、自動處理所有日曆邊界、代碼可讀性最強。配合 DateTime 類應對複雜日期運算,徹底告別手動天數計算的坑。