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

PHP 日期時間處理大全:date() 格式化、Unix 時間戳轉換、strtotime 相對時間計算實戰

     編輯:PHP 相關知識

時區設置 (必做第一步)

<?php
// php.ini 永久生效
date.timezone = Asia/Shanghai

// 運行時動態設置
date_default_timezone_set('Asia/Shanghai');
// 或
ini_set('date.timezone', 'Asia/Shanghai');

支持時區列表:PHP 官方文檔

date() 格式化字符完整速查表

類別字符說明示例
日d月份第幾天,2位補零01-31
j月份第幾天,不補零1-31
S英文序數後綴st, nd, rd, th
z年份第幾天0-365
周l完整星期名Sunday-Saturday
D3字母縮寫Mon-Sun
NISO-8601 數字周幾1(一)-7(日)
w數字周幾0(日)-6(六)
W年份第幾周42
月F完整月份名January-December
m2位數字月份01-12
M3字母縮寫Jan-Dec
n數字月份1-12
t當月天數28-31
年L是否閏年1/0
oISO-8601 年份1999/2003
Y4位年份2024
y2位年份24
時間aam/pm 小寫am
AAM/PM 大寫PM
BSwatch Beat000-999
g12小時制不補零1-12
G24小時制不補零0-23
h12小時制補零01-12
H24小時制補零00-23
i分鐘補零00-59
s秒補零00-59
時區e時區標識UTC, Asia/Shanghai
I是否夏令時1/0
T時區縮寫CST, EST
Z時區偏移秒數-43200~43200
完整格式cISO 86012024-01-15T14:30:00+08:00
rRFC 822Mon, 15 Jan 2024 14:30:00 +0800
UUnix 時間戳1705309800

時間戳獲取三大函數


// 1. time() - 當前時間戳
$now = time(); // 等同 date('U')

// 2. mktime() - 指定日期時間生成時間戳
$ts = mktime(14, 30, 0, 1, 15, 2024); // 2024-01-15 14:30:00
// 參數順序:時、分、秒、月、日、年、is_dst(已棄用)

// 3. strtotime() - 英文自然語言解析 (最強大)
strtotime('now');                    // 當前
strtotime('2024-01-15');             // 指定日期
strtotime('+1 day');                 // 明天
strtotime('+1 week 2 days 4 hours'); // 復雜相對時間
strtotime('next Thursday');          // 下個周四
strtotime('last Monday');            // 上個周一
strtotime('first day of this month');// 本月1號
strtotime('last day of next month'); // 下月最後一天

常用計算實例

1. 計算年齡

$birth = mktime(0,0,0, 1, 1, 1990);
$age = floor((time() - $birth) / (365.25*24*3600)); // 考慮閏年

2. 日期加減 (推薦 strtotime)

$tomorrow = date('Y-m-d', strtotime('+1 day'));
$nextMon  = date('Y-m-d', strtotime('next Monday'));
$monthEnd = date('Y-m-d', strtotime('last day of this month'));

3. 獲取日期各組件 (getdate)

$info = getdate(); // 可傳時間戳
// 返回關鍵鍵:seconds, minutes, hours, mday, wday, mon, year, yday, weekday, month, 0(時間戳)

4. 兩日期差天數 (DateTime 現代寫法 PHP 5.3+)

$d1 = new DateTime('2024-01-01');
$d2 = new DateTime('2024-12-31');
$diff = $d1->diff($d2);
echo $diff->days; // 365
echo $diff->format('%a 天 %h 小時 %i 分鐘');

MySQL 日期時間字段互轉

場景PHP → MySQLMySQL → PHP
DATETIMEdate('Y-m-d H:i:s', $ts)strtotime($row['dt'])
TIMESTAMPdate('Y-m-d H:i:s', $ts)strtotime($row['ts'])
DATEdate('Y-m-d', $ts)strtotime($row['dt'])
INT(11) 存時間戳$ts$row['ts'] (直接用)

最佳實踐清單

  1. 入口文件統一 date_default_timezone_set('Asia/Shanghai');。
  2. 2. 業務代碼優先使用 DateTime / DateTimeImmutable 物件,避免 2038 年問題 (32位系統 time_t 溢出)。 3. 數據庫存儲統一用 DATETIME 或 TIMESTAMP,應用層轉換集中在 Repository/Mapper 層。 4. 定時任務/排程務必用 UTC 存儲,顯示時再按用戶時區轉換。 5. 單元測試覆蓋閏年、夏令時切換、月末跨月等邊界。
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved