善用 strtotime() 強大的相對時間解析功能,輕鬆完成日期加減運算:取得下週同一天、N 天前/後、月底、下個月第一天等。
$date = '2013-01-01';
$nextWeek = date('Y-m-d', strtotime('$date + 7 days'));
$prevMonth = date('Y-m-d', strtotime('$date - 1 month'));
$firstDayNextMonth = date('Y-m-01', strtotime('+1 month'));
$lastDayThisMonth = date('Y-m-t'); // t = 本月總天數
$date1 = '2010-07-01';
$date2 = '2010-07-08';
$diffDays = abs(strtotime($date1) - strtotime($date2)) / 86400;
echo $diffDays; // 7
| 格式 | 說明 |
|---|---|
+1 day / -1 day | 後/前一天 |
+1 week / -2 weeks | 週數 |
+1 month / -3 months | 月份 (自動處理月底邊界) |
+1 year | 年份 |
next Monday / last Friday | 下/上一個指定週几 |
first day of next month | 下月第一天 (PHP 5.3+) |
last day of this month | 本月最後一天 (PHP 5.3+) |
DateTime + DateInterval:(new DateTime('2024-01-31'))->add(new DateInterval('P1M'))->format('Y-m-d'); 正確得到 2024-02-29 (閏年) 而非 3/2/3。strtotime() 對「月份邊界」處理有時違反直覺(如 1/31 +1 month → 3/2/3),DateTime 行為更一致。date_default_timezone_set()。