strtotime(string $datetime, int $baseTimestamp = time()): int|false
將英文日期時間描述解析為 Unix 時間戳(自 1970-01-01 00:00:00 UTC 秒數)。失敗返回 false(PHP 5.1.0 前為 -1)。
| 輸入字串 | 說明 |
|---|---|
"now" | 當前時間 |
"3 October 2005" | 標準日期 |
"+5 hours" | 相對時間:5 小時後 |
"+1 week 3 days 7 hours 5 seconds" | 複合相對時間 |
"next Monday" | 下一個周一 |
"last Sunday" | 上一個周日 |
"yesterday" / "tomorrow" | 昨天/明天 |
"first day of next month" | 下月第一天(PHP 5.3+) |
strtotime() 使用 date_default_timezone_get() 返回的時區(優先順序:date_default_timezone_set() > TZ 環境變數 > php.ini date.timezone > 系統推測 > UTC)。
date_default_timezone_set('Asia/Taipei');
echo date('Y-m-d H:i:s', strtotime('2024-01-01')); // 2024-01-01 00:00:00 (CST)
date_default_timezone_set('UTC');
echo date('Y-m-d H:i:s', strtotime('2024-01-01')); // 2024-01-01 00:00:00 (UTC)
// 獲取當前腳本默認時區
echo date_default_timezone_get(); // Asia/Taipei
// 設定腳本時區(建議在 bootstrap 階段統一設定)
date_default_timezone_set('Asia/Shanghai');
strtotime("05-06-07") 視為 2005-06-07(Y-m-d)而非 2007-05-06。統一用 Y-m-d 或 Y/m/d。DateTime 物件。strtotime("+1 month", strtotime("2024-01-31")) 返回 2024-03-03(因 2 月無 31 日)。用 "first day of +1 month" 或 DateTime::modify('first day of next month') 避免。DateTime::createFromFormat() 比 strtotime() 快 3~5 倍。$dt = new DateTime('+1 week 3 days', new DateTimeZone('Asia/Taipei'));
echo $dt->format('Y-m-d H:i:s');
$dt2 = DateTime::createFromFormat('Ymd', '20240101');
echo $dt2->format('Y-m-d');