首頁
編程語言
C語言|JAVA編程
Python編程
網頁編程
ASP編程|PHP編程
JSP編程
數據庫
MYSQL數據庫|SqlServer數據庫
Oracle數據庫|DB2數據庫
您现在的位置: 程式碼之家 >> 編程語言 >  >> 網頁程式設計 >> PHP 程式設計 >> PHP 相關知識

PHP 日期時間運算:strtotime() 相對格式完整速查表

     編輯:PHP 相關知識

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 更快、更安全。

現代寫法:DateTimeImmutable (PHP 5.5+)

<?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');
?>
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved