strtotime() 是 PHP 中最強大、最靈活的時間解析函數,能將各種格式的英文時間文字描述轉換為 Unix 時間戳(自 1970-01-01 00:00:00 UTC 起的秒數)。
// 標準日期時間格式
echo date('Y-m-d H:i:s', strtotime('2016-01-30 18:00'));
// 輸出:2016-01-30 18:00:00
// 緊湊格式(無分隔符)
echo date('Y-m-d H:i:s', strtotime('20160130180001'));
// 輸出:2016-01-30 18:00:01
這是 strtotime() 最迷人的特性——支援人類自然語言:
// 昨天
echo date('Y-m-d H:i:s', strtotime('yesterday'));
// 上週
echo date('Y-m-d H:i:s', strtotime('last week'));
// 本週開始時間(週一 00:00:00)
echo date('Y-m-d H:i:s', strtotime('this week midnight'));
// 本月開始時間
echo date('Y-m-d H:i:s', strtotime('first day of this month midnight'));
// 相對計算:下個月這個時間
echo date('Y-m-d H:i:s', strtotime('+1 month'));
| 類別 | 範例 | 說明 |
|---|---|---|
| 相對時間 | +1 day, -2 weeks, +3 months | 支援正負號與單位組合 |
| 週期描述 | next Monday, last Friday | 下週一、上週五 |
| 月份邊界 | first day of, last day of | 月初、月末 |
| 特定時間 | noon, midnight, 10:30am | 中午、午夜、具體時間 |
| 複雜組合 | first Monday of next month | 下個月第一個週一 |
完整的 PHP 時間描述格式文檔請參考:
// 強烈建議在腳本開頭設置時區
date_default_timezone_set('Asia/Taipei');
// 或在 php.ini 中設置:date.timezone = Asia/Taipei
如前文所述,32 位系統上 strtotime() 最大只能解析到 2038-01-19。長期項目建議使用 64 位環境或 DateTime 類。
// 避免使用歧義格式
strtotime('02/03/2016'); // 美式解析為 2月3日,歐式為 3月2日
// 推薦使用 ISO 8601 格式
strtotime('2016-03-02'); // 無歧義
$dt = new DateTime('next Monday');
echo $dt->format('Y-m-d'); // 更物件化、功能更強大
掌握 strtotime() 的豐富語法,能讓你的時間處理代碼更簡潔、更符合人類直覺,是 PHP 開發者必備的核心技能之一。