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

PHP strtotime() 時間戳轉換完全指南

     編輯:PHP 綜合知識

核心函數對比

  • time():取得當前 Unix 時間戳(秒)。
  • strtotime():將**英文文字日期描述**解析為 Unix 時間戳,支援相對時間、絕對日期、週期表達。
  • date():將時間戳格式化為可讀字串。

常用場景範例

指定日期轉時間戳

<?php
echo strtotime('2012-12-7'); // 1354838400 (2012-12-07 00:00:00 UTC)
?>

當前時間戳

<?php
echo time(); // 當前秒數
echo intval(time()); // 強制整數
?>

時間戳轉日期字串

<?php
echo date('Y-m-d H:i:s', time()); // 2024-01-15 14:30:00
?>

相對時間表達威力

strtotime() 支援豐富的自然語言:

<?php
echo strtotime('now');                    // 現在
echo strtotime('10 September 2000');      // 絕對日期
echo strtotime('+1 day');                 // 明天這時
echo strtotime('+1 week');                // 下週這時
echo strtotime('+1 week 2 days 4 hours 2 seconds'); // 複合相對時間
echo strtotime('next Thursday');          // 下個週四 00:00:00
echo strtotime('last Monday');            // 上個週一 00:00:00
?>

實戰對照表(假設當前 2009-01-22 09:40:25)

表達式結果時間戳格式化日期
+1 daystrtotime('+1 day')2009-01-23 09:40:25
-1 daystrtotime('-1 day')2009-01-21 09:40:25
+1 weekstrtotime('+1 week')2009-01-29 09:40:25
-1 weekstrtotime('-1 week')2009-01-15 09:40:25
next Thursdaystrtotime('next Thursday')2009-01-29 00:00:00
last Thursdaystrtotime('last Thursday')2009-01-15 00:00:00

進階技巧

結合 mktime() 精確控制

<?php
// 取得本月第一天 00:00:00
$firstDay = mktime(0, 0, 0, date('n'), 1, date('Y'));

// 取得本月最後一天 23:59:59
$lastDay = mktime(23, 59, 59, date('n') + 1, 0, date('Y'));
?>

處理時區

<?php
date_default_timezone_set('Asia/Taipei');
echo date('Y-m-d H:i:s', strtotime('2024-01-01')); // 正確顯示台北時間
?>

避免 32 位系統 2038 年問題

PHP 7.1+ 在 64 位系統上 strtotime() 支援 64 位整數,可處理 2038 年後日期。32 位系統建議改用 DateTime 類:

<?php
$dt = new DateTime('2050-01-01');
echo $dt->getTimestamp(); // 需 64 位 PHP
echo $dt->format('Y-m-d H:i:s'); // 安全輸出
?>

常見陷阱

  • 月份邊界:strtotime('+1 month', '2024-01-31') 會回傳 3 月 3 日(因 2 月無 31 日),建議用 'first day of +1 month'。
  • 英文環境依賴:strtotime() 解析依賴英文月份/星期名稱,非英文環境需自行轉換。
  • 回傳 false:解析失敗回傳 false(PHP 5.1+),舊版回傳 -1,務必檢查。

總結

strtotime() 是 PHP 日期時間處理的瑞士刀,配合 date()、DateTime 類,能優雅解決絕大多數業務時間計算需求。

  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved