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

PHP 日期時間函式完整速查表:date、strtotime、DateTime、格式化參數

     編輯:PHP 相關知識

date() 格式化字元完整表

字元說明範例
Y4 位數年2024
y2 位數年24
m月份 (01-12)01
n月份 (1-12)1
F月份英文全名January
M月份英文縮寫Jan
d日期 (01-31)15
j日期 (1-31)15
l星期幾全名Monday
D星期幾縮寫Mon
w星期幾數字 (0=日)1
NISO 星期幾 (1=一)1
H24 小時制 (00-23)14
h12 小時制 (01-12)02
i分鐘 (00-59)30
s秒數 (00-59)59
aam/pm 小寫pm
AAM/PM 大寫PM
UUnix 時間戳1705312259
cISO 86012024-01-15T14:30:59+08:00
rRFC 2822Mon, 15 Jan 2024 14:30:59 +0800

strtotime() 相對時間字串

strtotime('now');           // 現在
strtotime('+1 day');        // 明天
strtotime('-1 week');       // 一週前
strtotime('first day of this month'); // 本月 1 號
strtotime('last day of next month');  // 下月最後一天
strtotime('next Monday');   // 下個週一
strtotime('+3 months -2 days');       // 組合

DateTime 物件導向 API (推薦)

$dt = new DateTime('2024-01-15 14:30:00', new DateTimeZone('Asia/Taipei'));
$dt->modify('+1 day');
$dt->setTime(9, 0, 0);
echo $dt->format('Y-m-d H:i:s'); // 2024-01-16 09:00:00

// 差值
$diff = $dt1->diff($dt2);
echo $diff->days; // 天數差
echo $diff->format('%h小時%i分'); // 格式化差值

// 區間迭代
$period = new DatePeriod($start, new DateInterval('P1D'), $end);
foreach ($period as $d) { ... }

常用函式速查

函式用途回傳
time()當前 Unix 時間戳int
microtime(true)含微秒的浮點時間戳float
mktime(h,i,s,m,d,Y)組合日期時間為時間戳int
getdate(ts)時間戳轉關聯陣列array
checkdate(m,d,Y)驗證日期合法性bool
date_default_timezone_set()設定預設時區void
DateTimeZone::listIdentifiers()列出所有时区array

時區處理最佳實踐

  1. 程式啟動即設定:date_default_timezone_set('Asia/Taipei');
  2. 資料庫儲存 **UTC** 時間戳或 DATETIME (不含時區)
  3. 顯示時依用戶時區轉換:$dt->setTimezone(new DateTimeZone($userTz))
  4. 避免在字串拼接中混用時區

常見陷阱

  • strtotime('2024-02-30') 回傳 false (PHP 5.3+) 或錯誤日期 (舊版)
  • date('Y-m-d', strtotime('-1 month')) 在 3/31 會得到 3/03 (非 2/28),建議用 first day of -1 month
  • new DateTime('@'. $timestamp) 需加 @ 前綴表示 Unix 時間戳
  1. 上一篇文章:
  2. 下一篇文章:
Copyright © 程式碼之家 All Rights Reserved