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

PHP 日期時間操作技巧:靈活輸出任意時間點完整指南

     編輯:PHP 相關知識

前言

在 PHP 開發中,根據相對時間輸出特定日期(如「前一天」、「下個月」、「兩小時後」)是常見需求。結合 strtotime() 與 date() 函數,即可輕鬆實現任意時間點的計算與格式化輸出。

核心代碼範例

<?php
// 設定時區(必須,避免時區偏差)
date_default_timezone_set('Asia/Shanghai');

// 取得前一天的日期時間
$a = date('Y-m-d H:i:s', strtotime('-1 day'));
echo $a;  // 輸出格式:2024-01-15 14:30:00
?>

相對時間語法完整對照表

strtotime() 支援豐富的自然語言時間描述:

語法含義範例
-1 year / +1 year前一年 / 明年strtotime('-1 year')
-1 month / +1 month上個月 / 下個月strtotime('+1 month')
-1 day / +1 day昨天 / 明天strtotime('-1 day')
-1 hour / +1 hour一小時前 / 一小時後strtotime('+1 hour')
-1 minute / +1 minute一分鐘前 / 一分鐘後strtotime('-1 minute')
-1 second / +1 second一秒前 / 一秒後strtotime('+1 second')
next Monday下週一strtotime('next Monday')
last Friday上週五strtotime('last Friday')
first day of this month本月第一天strtotime('first day of this month')
last day of next month下月最後一天strtotime('last day of next month')

進階應用場景

1. 計算特定格式的相對時間

<?php
// 只輸出日期
echo date('Y-m-d', strtotime('-1 week'));        // 一週前
echo date('Y-m-d', strtotime('+2 weeks'));       // 兩週後

// 只輸出時間
echo date('H:i:s', strtotime('-30 minutes'));    // 30分鐘前

// 自訂格式
echo date('Y年m月d日 H點i分', strtotime('+1 year')); // 一年後(中文格式)
?>

2. 結合當前時間進行運算

<?php
$now = time();  // 當前時間戳
echo date('Y-m-d H:i:s', $now - 86400);        // 24小時前(86400秒)
echo date('Y-m-d H:i:s', $now + 3600);         // 1小時後
echo date('Y-m-d H:i:s', strtotime('+3 days', $now)); // 3天後(指定基準時間)
?>

3. 業務邏輯常用範例

<?php
// 會員到期提醒:7天前發送通知
$expiry = strtotime('2024-12-31 23:59:59');
$remind = strtotime('-7 days', $expiry);
if (time() >= $remind && time() < $expiry) {
    echo "發送續費提醒通知";
}

// 文章發布時間顯示「X天前」
$publishTime = strtotime('2024-01-10 10:00:00');
$diff = time() - $publishTime;
$days = floor($diff / 86400);
echo "發布於 $days 天前";
// 更完整的相對時間顯示請參考文章 ID 154225
?>

關鍵注意事項

  1. 時區設定: 生產環境務必在 php.ini 或代碼開頭設定 date_default_timezone_set(),否則會使用伺服器預設時區導致偏差
  2. 夏令時間: 跨夏令時間切換點計算時,strtotime() 會自動處理,但需確認時區資料庫更新
  3. 32位系統限制: 32位 PHP 時間戳範圍為 1901-2038 年,超出範圍請使用 DateTime 類別
  4. 格式字元: date() 格式參數區分大小寫(m=月份,M=英文月份縮寫)

現代化替代方案:DateTime 類別

PHP 5.2+ 建議使用物件導向的 DateTime,功能更強大、避免 32 位限制:

<?php
$dt = new DateTime('now', new DateTimeZone('Asia/Shanghai'));
$dt->modify('-1 day');
echo $dt->format('Y-m-d H:i:s');

// 連續修改
$dt = new DateTime();
$dt->modify('+1 week')->modify('+3 hours')->modify('-15 minutes');
echo $dt->format('Y-m-d H:i:s');
?>

總結

掌握 strtotime() 相對時間語法與 date() 格式化,配合正確時區設定,即可滿足 90% 以上的日期時間運算需求。複雜場景建議升級使用 DateTime 類別,獲得更好的可讀性與擴展性。

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