PHP 所有時間函數基準為 1970-01-01 00:00:00 UTC 起經過的秒數(整數),即 Unix Timestamp。
| 函數 | 說明 | 典型用法 |
|---|---|---|
date(format, ts?) | 格式化輸出字串 | date('Y-m-d H:i:s') |
getdate(ts?) | 回傳關聯陣列含完整時間成分 | $d=getdate(); echo $d['hours']; |
checkdate(m,d,Y) | 驗證日期合法性 | checkdate(2,29,2024) → true |
time() | 取得當前時間戳 | $now = time(); |
mktime(h,i,s,m,d,Y) | 由日期時間構造時間戳(自動修正溢位) | mktime(0,0,0,13,1,2024) → 2025-01-01 |
microtime(true) | 微秒級時間戳(float) | 效能測量、唯一 ID 生成 |
strtotime(str, now?) | 解析英文相對時間為時間戳 | strtotime('+1 week') |
strftime(fmt, ts) | 區域化格式化(依 setlocale) | setlocale(LC_TIME,'zh_TW'); strftime('%Y年%m月') |
Y - 四位年份 (2024) y - 兩位年份 (24) m - 月份帶零 (01-12) n - 月份不帶零 (1-12) F - 月份全名 (January) M - 月份縮寫 (Jan) d - 日期帶零 (01-31) j - 日期不帶零 (1-31) l - 星期全名 (Monday) D - 星期縮寫 (Mon) w - 星期數 (0=週日-6) H - 24時帶零 (00-23) h - 12時帶零 (01-12) G - 24時不帶零 g - 12時不帶零 i - 分鐘 (00-59) s - 秒 (00-59) a/am pm / A/AM PM z - 年內第幾天 (0-365) U - 時間戳
<?php
$now = time();
echo "50小時後: " . date('H:i A l F dS, Y', mktime(date('H')+50)) . "<br>";
// 效能測量
$start = microtime(true);
for ($i=0;$i<1000;$i++) echo "good!";
$end = microtime(true);
echo "耗時: " . ($end-$start) . " 秒";
?>
物件導向、不可變、支援時區、無 2038 年問題:
$dt = new DateTime('now', new DateTimeZone('Asia/Taipei'));
$dt->modify('+1 week 2 days 4 hours');
echo $dt->format('Y-m-d H:i:s');
// 區間計算
$diff = $dt1->diff($dt2);
echo $diff->format('%a 天 %h 小時 %i 分鐘');
php.ini:date.timezone = Asia/Taipeidate_default_timezone_set('Asia/Taipei')E_WARNING 並預設 UTC。掌握 time()/date()/strtotime() 三大核心即可應對 80% 場景;複雜業務(時區、區間、不可變)請遷移至 DateTime 類別,避開 32 位時間戳陷阱。