萬盛學電腦網

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

PHP strtotime() 函數深度解析:原理、陷阱與「-1 month」失效根因

函數簽名與基本用法

strtotime(string $datetime, int $baseTimestamp = time()): int|false

將英文文本日期描述解析為 Unix 時間戳。支持相對時間、絕對日期、星期、節假日等豐富格式。

常用格式速查表

類別示例說明
相對時間+1 day, -2 weeks, +3 months, +1 year相對基準時間偏移
yesterday, tomorrow, now特殊關鍵字
first day of this month, last day of next monthPHP 5.3+ 月邊界關鍵字
星期操作monday, next monday, previous friday下一個/上一個星期幾
first day of, last day of月首/月尾
third wednesday本月第三個周三
時間點noon, midnight, 14:30, 2:30pm具體時間
時區GMT, UTC, +0800, America/New_York時區指定

核心實現原理:re2c 詞法分析 + 狀態機

PHP 使用 re2c 生成詞法分析器(源碼:ext/date/lib/parse_date.re),將輸入字符串按規則分詞,構建 timelib_time 結構體,再由 timelib_update_ts() 計算最終時間戳。

關鍵結構體

struct timelib_time {
    timelib_sll y, m, d;      // 年月日
    timelib_sll h, i, s;      // 時分秒
    double f;                 // 微秒
    int z;                    // GMT 偏移(分鐘)
    char *tz_abbr;            // 時區縮寫
    timelib_tzinfo *tz_info;  // 時區詳情
    timelib_rel_time relative; // 相對時間調整量
    // ... 狀態標誌位
};

struct timelib_rel_time {
    timelib_sll y, m, d;      // 相對年月日
    timelib_sll h, i, s;      // 相對時分秒
    int weekday;              // 目標星期幾
    int weekday_behavior;     // 0=不計算當天 1=計算當天
    int first_last_day_of;    // 1=first 2=last
    int invert;               // 正負號
    // ...
};

「-1 month」失效根因深度剖析

解析流程

  1. 詞法分析識別 relnumber = -1、reltextunit = month。
  2. 進入 relative 規則,設置 relative.m = -1。
  3. 計算階段:timelib_update_ts() 直接執行 time->m += relative.m(即月份 -1)。
  4. 關鍵點: 日字段 time->d 保持不變(仍為 31)。
  5. 後續標準化:timelib_do_normalize() 檢測日期無效(2月無 31 日),按「天數溢出」邏輯向後滾動:31 - 28 = 3 → 3 月 3 日。

源碼級還原

// 簡化版 timelib_do_normalize 邏輯
while (time->d > days_in_month(time->y, time->m)) {
    time->d -= days_in_month(time->y, time->m);
    time->m++;
    if (time->m > 12) { time->m = 1; time->y++; }
}

為什麼這不是 Bug?

這符合「日曆算術」語義:「同日期下個月」。若 3 月 31 日減一個月,語義上是「2 月 31 日」,因不存在,自然順延。但業務常期望「上個月最後一天」,故需自定義邏輯。

關鍵字處理細節

first / last / previous / next / this

// first day of this month -> time->d = 1
// last day of this month  -> time->d = 0; time->m++; (下個月第0天 = 本月最後一天)
// previous monday         -> relative.d = -7; relative.weekday = 1; relative.weekday_behavior = 0;
// next friday             -> relative.d = +7; relative.weekday = 5; relative.weekday_behavior = 0;
// this thursday           -> relative.weekday = 4; relative.weekday_behavior = 1; (包含今天)

back of / front of(小時邊界)

// back of 10  -> 設置為 10:15 (10點後15分)
// front of 10 -> 設置為 09:45 (10點前15分)
// back of 24  -> 翌日 00:15
// front of 0  -> 前日 23:45

最佳實踐:避開 strtotime 陷阱

1. 月份運算用「首日/末日」關鍵字

// 正確獲取上個月同一天(或最後一天)
$ts = strtotime('2011-03-31');
echo date('Y-m-d', strtotime('last day of last month', $ts)); // 2011-02-28 ✅

// 獲取上個月第一天
echo date('Y-m-d', strtotime('first day of last month', $ts)); // 2011-02-01

2. 關鍵業務邏輯封裝為工具函數

function getLastMonthSameDay(int $timestamp): int {
    $dt = new DateTime('@' . $timestamp);
    $dt->modify('first day of last month');
    $lastDay = (int)$dt->format('t');
    $day = (int)$dt->format('j');
    $dt->setDate($dt->format('Y'), $dt->format('m'), min($day, $lastDay));
    return $dt->getTimestamp();
}

3. 避免歧義格式

  • 03/04/2024:美式 mm/dd vs 歐式 dd/mm → 永遠使用 ISO 8601: 2024-03-04。
  • next monday:PHP 返回「下一個周一」,若今天是周一則返回下周一;this monday 返回本周一(含今天)。

性能與緩存

  • strtotime 內部無緩存,重複解析相同字符串有開銷。
  • 高頻調用(如日曆渲染)建議預解析緩存:$cache[$str] = strtotime($str);。
  • PHP 7+ DateTime::createFromFormat 解析固定格式比 strtotime 快 3-5 倍。

總結

strtotime() 功能強大但語義隱含「日曆算術」邏輯,月份運算易產生業務預期偏差。核心建議: 關鍵日期計算改用 DateTime + modify('first/last day of ...') 明確語義;解析固定格式用 DateTime::createFromFormat;保留 strtotime 處理自由文本輸入(如用戶輸入「下周五」)。

copyright © 萬盛學電腦網 all rights reserved