strtotime() 相對格式完整速查表strtotime() 支援極豐富的相對時間字串,是訂閱到期、排程、報表篩選的利器。本文整理常用格式與陷阱。
<?php
// 目前時間 + 相對修飾
echo date('Y-m-d H:i:s', strtotime('+1 month')); // 一個月後
echo date('Y-m-d', strtotime('+2 weeks')); // 兩週後
echo date('Y-m-d', strtotime('next Monday')); // 下周一
echo date('Y-m-d', strtotime('last day of next month'));// 下月最後一天
?>
| 需求 | 字串範例 | 說明 |
|---|---|---|
| N 年/月/週/日/時/分/秒後 | +N year|month|week|day|hour|minute|second | 支援複數 s,如 +3 months |
| 下一個/上一個 星期幾 | next Monday / last Friday | 英文星期名 |
| 本月第一天/最後一天 | first day of this month / last day of this month | 避免月份天數不一問題 |
| 下月同一天 | +1 month (注意 1/31 → 2/28 或 3/3) | 邊界自動調整 |
| 特定時間基準 | strtotime('+1 month', $timestamp) | 第二參數指定基準時間 |
<?php
$now = time();
// 包月會員
$expireMonth = date('Y-m-d H:i:s', strtotime('+1 month', $now));
// 包年會員
$expireYear = date('Y-m-d H:i:s', strtotime('+1 year', $now));
// 試用 7 天
$expireTrial = date('Y-m-d H:i:s', strtotime('+7 days', $now));
// 儲存為 timestamp 方便比對
$expireTs = strtotime('+1 month', $now);
?>
strtotime('+1 month', strtotime('2024-01-31')) → 2024-03-02 (因 2 月無 31 日)。'first day of +1 month' 或 DateTime 物件 modify('first day of +1 month')。strtotime 使用 date_default_timezone_set() 設定的時區,建議統一用 UTC 存儲,顯示時再轉換。DateTimeImmutable 物件比重複呼叫 strtotime 更快、更安全。<?php
$dt = new DateTimeImmutable('now', new DateTimeZone('Asia/Taipei'));
$expire = $dt->modify('+1 month')->setTime(0,0,0); // 下個月同一天 00:00
echo $expire->format('Y-m-d H:i:s');
// 避開月份邊界:下個月第一天
$firstNext = $dt->modify('first day of +1 month');
?>