萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 網路程式設計 >> PHP 程式設計

PHP strtotime() 函數深度解析:用法、核心原理與「-1 month」陷阱完整指南

strtotime() 是 PHP 處理日期時間字串解析的核心函數,看似簡單卻暗藏許多邊界行為(如 strtotime("-1 month") 在月底計算易出錯)。本文從 C 原始碼層面剖析其解析流程、相對時間計算邏輯,並總結實戰中常見陷阱與最佳實踐。

核心用法速查表

輸入範例說明輸出示例 (基準 2024-03-31)
strtotime("January") / strtotime("JAN")指定月份的今天;若該月無此日則順延2024-01-31 → 2024-03-02 (順延)
strtotime("first sunday", $ts)指定時間所在月的第一個星期日2024-01-07
strtotime("previous sunday", $ts)指定時間之前的最近一個星期日2024-03-24
strtotime("last day", $ts)指定月份的最後一天 (等同 date("t"))2024-02-29
strtotime("back of 24", $ts)指定小時的下一個小時 15 分 (24 → 翌日 00:15)2024-04-01 00:15:00
strtotime("front of 0", $ts)指定小時的上一個小時 45 分 (0 → 前日 23:45)2024-03-30 23:45:00

原始碼級實現原理 (基於 PHP 7.4+ / ext/date/lib/parse_date.re)

1. 詞法解析:re2c 生成的狀態機

PHP 使用 re2c 將 parse_date.re 編譯為高效的 DFA 狀態機。輸入字串逐字元掃描,匹配關鍵字 (yesterday, next, +1 day 等) 觸發對應的 TIMELIB_* 巨集操作 timelib_time 結構體的 relative 字段。

例如 "yesterday" 觸發:

'yesterday' {
    DEBUG_OUTPUT("yesterday");
    TIMELIB_INIT;
    TIMELIB_HAVE_RELATIVE();
    TIMELIB_UNHAVE_TIME();
    s->time->relative.d = -1;  // 相對天數 -1
    TIMELIB_DEINIT;
    return TIMELIB_RELATIVE;
}

2. 核心結構體

typedef struct timelib_time {
    timelib_sll y, m, d, h, i, s;       // 絕對日期時間
    timelib_sll z;                      // 時區偏移秒數
    timelib_rel_time *relative;         // 相對時間調整量
    timelib_tzinfo *tz_info;            // 時區資訊
    // ... 其他字段
} timelib_time;

typedef struct timelib_rel_time {
    timelib_sll y, m, d, h, i, s;       // 年月日時分秒相對增量
    int weekday, weekday_behavior;      // 星期幾調整
    int first_last_day_of;              // first/last day of month
    // ...
} timelib_rel_time;

3. 解析主流程 timelib_strtotime()

  1. 初始化基準時間:若提供 $now 參數,建構 timelib_time 作為基準;否則使用 time() 當前時間
  2. 詞法掃描與語義動作:re2c 掃描器識別 tokens,執行語義動作填充 relative 結構
  3. 填補缺失字段:timelib_fill_holes() 以基準時間補全未指定的年月日時分秒
  4. 應用相對調整:timelib_update_ts() 將 relative 增量疊加到基準時間
  5. 時區正規化:根據 tz_info 轉換為 UTC 時間戳
  6. 錯誤檢查與返回:檢查解析錯誤計數,回傳 Unix timestamp 或 false

「-1 month」陷阱:為什麼 3 月 31 日減一個月不是 2 月 28/29 日?

根本原因:PHP 的相對月份計算僅修改月份字段,保持日字段不變,然後由 timelib_update_ts() 進行「正規化」——若日超出目標月份範圍,自動順延到下個月。

// 簡化邏輯
$time->relative.m = -1;  // 月份 -1
// 正規化時:
// 2024-03-31 -> 月份變 2 -> 2024-02-31 -> 不存在 -> 正規化為 2024-03-02 (閏年) 或 2024-03-03 (平年)

正確取得「上個月同一天」的三種寫法

// 方法 1:先設為本月 1 日,再減 1 月 (最推薦,語意清晰)
$firstDayThisMonth = strtotime('first day of this month');
$firstDayLastMonth = strtotime('-1 month', $firstDayThisMonth);
$targetDay = min(date('j'), date('t', $firstDayLastMonth)); // 取當前日與上月天數較小值
$result = strtotime("{$targetDay} day", $firstDayLastMonth);

// 方法 2:使用 DateTime 物件 (PHP 5.3+,物件導向、鏈式呼叫)
$dt = new DateTime('2024-03-31');
$dt->modify('first day of this month')->modify('-1 month')->modify('+' . (min($dt->format('j'), $dt->format('t')) - 1) . ' days');
echo $dt->format('Y-m-d'); // 2024-02-29

// 方法 3:直接計算目標月份首日,再加天數 (效能最佳)
$year = 2024; $month = 3; $day = 31;
$targetMonth = $month - 1; $targetYear = $year;
if ($targetMonth == 0) { $targetMonth = 12; $targetYear--; }
$daysInTargetMonth = cal_days_in_month(CAL_GREGORIAN, $targetMonth, $targetYear);
$actualDay = min($day, $daysInTargetMonth);
echo date('Y-m-d', mktime(0,0,0, $targetMonth, $actualDay, $targetYear)); // 2024-02-29

其他常見陷阱與避坑指南

  • 兩位數年份歧義:strtotime("00-01-01") 視為 2000-01-01,strtotime("69-12-31") 視為 1969-12-31 (POSIX 標準)
  • 時區陷阱:未設定 date_default_timezone_set() 時使用系統時區,跨時區部署極易出錯,**務必在入口檔案統一設定 UTC**
  • 夏令時轉換:strtotime("+1 day") 在夏令時切換日可能非 86400 秒,跨日計算請用 DateTime::add(new DateInterval('P1D'))
  • 效能考量:大量迴圈解析固定格式日期時,DateTime::createFromFormat() 或 strptime() 比 strtotime() 快 3-5 倍

現代化替代方案:DateTime Immutable (PHP 7.1+)

// 不可變物件,執行緒安全,鏈式操作不改變原物件
$dt = new DateTimeImmutable('2024-03-31 15:30:00', new DateTimeZone('Asia/Taipei'));
$lastMonthSameDay = $dt->modify('first day of this month')
                       ->modify('-1 month')
                       ->modify('+'.(min($dt->format('j'), $dt->format('t'))-1).' days');
echo $lastMonthSameDay->format('Y-m-d H:i:s'); // 2024-02-29 15:30:00

結語

strtotime() 功能強大但語意隱晦,涉及月份/年份跨度計算時,請優先使用 DateTime 物件配合明確語意方法 (first day of, last day of)。理解其底層「修改月份字段再正規化」機制,能幫您避開 90% 的日期計算坑。建立專案統一的日期處理工具類,封裝常用業務邏輯(如「取得上個月同一天」、「取得本季度首尾日」),是長期維護的明智之舉。

copyright © 萬盛學電腦網 all rights reserved