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

PHP strtotime() 時間戳轉換完全指南:相對時間、格式化、常見陷阱

     編輯:PHP 相關知識

核心函數

  • time():取得當前 Unix 時間戳(秒)
  • strtotime($datetime, $baseTimestamp):解析英文文字日期時間描述為 Unix 時間戳
  • date($format, $timestamp):格式化時間戳為字串

常用 strtotime 相對時間語法

輸入字串含義範例輸出
now現在當前時間戳
+1 day明天這時+86400 秒
-1 day昨天這時-86400 秒
+1 week下週這時+604800 秒
+1 week 2 days 4 hours 2 seconds組合相對時間依序疊加
next Thursday下個星期四 00:00下週四凌晨
last Monday上個星期一 00:00上週一凌晨
first day of this month本月 1 號 00:00月首
last day of next month下月最後一天 23:59:59月末
2023-12-25指定日期(ISO 8601)該日 00:00
2023-12-25 14:30:00指定日期時間該時刻

程式碼範例


echo strtotime("now") . "\n";
echo strtotime("10 September 2000") . "\n";
echo strtotime("+1 day") . "\n";
echo strtotime("+1 week") . "\n";
echo strtotime("+1 week 2 days 4 hours 2 seconds") . "\n";
echo strtotime("next Thursday") . "\n";
echo strtotime("last Monday") . "\n";

// 格式化輸出
echo date("Y-m-d H:i:s", time()) . "\n";                    // 當前
echo date("Y-m-d H:i:s", strtotime("+1 day")) . "\n";       // 明天
echo date("Y-m-d H:i:s", strtotime("-1 day")) . "\n";       // 昨天
echo date("Y-m-d H:i:s", strtotime("+1 week")) . "\n";      // 下週
echo date("Y-m-d H:i:s", strtotime("-1 week")) . "\n";      // 上週
echo date("Y-m-d H:i:s", strtotime("next Thursday")) . "\n";// 下週四
echo date("Y-m-d H:i:s", strtotime("last Thursday")) . "\n";// 上週四

指定日期轉時間戳


// 字串格式建議用 ISO 8601 (YYYY-MM-DD) 避免歧義
$ts = strtotime('2023-12-25'); // 2023-12-25 00:00:00
$ts = strtotime('2023-12-25 14:30:00');

常見陷阱與最佳實踐

1. 月份邏輯陷阱


// 1 月 31 日執行
echo date('Y-m-d', strtotime('+1 month')); // 3 月 3 日(非 2 月 31 日)
// 建議用:
echo date('Y-m-d', strtotime('first day of +1 month')); // 2 月 1 日

2. 時區問題


// 腳本開頭設定時區(預設 UTC)
date_default_timezone_set('Asia/Taipei'); // 或 Asia/Shanghai
// 或 php.ini: date.timezone = Asia/Taipei

3. 32 位元系統 2038 年問題

32 位元 PHP 整數最大值約 2038-01-19,超過會溢位。現代環境請使用 64 位元 PHP 或 DateTime 類別。

4. 使用 DateTime 類別(物件導向、無 2038 問題、支援微秒)


$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));
$dt->modify('+1 week');
echo $dt->format('Y-m-d H:i:s');

$dt2 = DateTime::createFromFormat('Y-m-d H:i:s', '2023-12-25 14:30:00');
echo $dt2->getTimestamp(); // 取得時間戳

效能提示

  • time() 比 strtotime('now') 快(無解析開銷)。
  • 大量日期運算請用 DateTime 物件複用,避免重複建立。
  • 資料庫層面盡量用 NOW(), DATE_ADD() 等函數,減少應用層運算。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved