PHP 日期時間格式化權威參考手冊
date() 是 PHP 最常用的日期格式化函數,掌握其格式化字符對開發效率至關重要。本文提供完整參數速查表、常用組合模式及時區處理最佳實踐。
基礎用法
<?php
// 當前日期時間
echo date("Y-m-d H:i:s"); // 2024-01-15 14:30:45
// 指定時間戳
echo date("Y-m-d", strtotime("+1 week")); // 一周後日期
?>
完整格式化字符速查表
| 字符 | 說明 | 示例輸出 |
| Y | 四位數年份 | 2024 |
| y | 兩位數年份 | 24 |
| m | 月份,補零 | 01-12 |
| n | 月份,不補零 | 1-12 |
| F | 月份全稱 | January |
| M | 月份縮寫 | Jan |
| d | 日期,補零 | 01-31 |
| j | 日期,不補零 | 1-31 |
| H | 24制小時,補零 | 00-23 |
| G | 24制小時,不補零 | 0-23 |
| h | 12制小時,補零 | 01-12 |
| g | 12制小時,不補零 | 1-12 |
| i | 分鐘,補零 | 00-59 |
| s | 秒,補零 | 00-59 |
| a | am/pm 小寫 | am/pm |
| A | AM/PM 大寫 | AM/PM |
| l | 星期全稱 | Monday |
| D | 星期縮寫 | Mon |
| w | 星期數字 | 0(日)-6(六) |
| N | ISO-8601 星期 | 1(一)-7(日) |
| z | 年間第幾天 | 0-365 |
| W | 年間第幾周 | 01-53 |
| t | 當月天數 | 28-31 |
| U | Unix 時間戳 | 1705312245 |
| c | ISO 8601 格式 | 2024-01-15T14:30:45+08:00 |
| r | RFC 2822 格式 | Mon, 15 Jan 2024 14:30:45 +0800 |
常用組合模式
<?php
// 標準日期時間
date("Y-m-d H:i:s"); // 2024-01-15 14:30:45
date("Y/m/d H:i"); // 2024/01/15 14:30
// 中文友好格式
date("Y年m月d日 H點i分"); // 2024年01月15日 14點30分
date("m月d日 D"); // 01月15日 Mon
// 精確時間戳
date("Y-m-d H:i:s.u"); // 含微秒 (需 PHP 7.0+)
date("U.u"); // 微秒級時間戳
// 週期計算
date("W", strtotime("Monday this week")); // 本周第幾周
date("t"); // 本月天數
?>
中文星期獲取技巧
<?php
$weekarray = ["日", "一", "二", "三", "四", "五", "六"];
echo "星期" . $weekarray[date("w")]; // 星期一
// 指定日期
echo "星期" . $weekarray[date("w", strtotime("2024-01-15"))]; // 星期一
?>
strtotime() 相對時間表達式
| 表達式 | 含義 | 示例 |
| +1 day | 明天 | strtotime("+1 day") |
| -1 week | 一周前 | strtotime("-1 week") |
| +1 month | 一個月後 | strtotime("+1 month") |
| next Monday | 下個周一 | strtotime("next Monday") |
| last Friday | 上個周五 | strtotime("last Friday") |
| first day of this month | 本月1號 | strtotime("first day of this month") |
| last day of next month | 下月最後一天 | strtotime("last day of next month") |
時區處理最佳實踐
<?php
// 設置默認時區(應用啟動時一次性設置)
date_default_timezone_set('Asia/Shanghai'); // 或 UTC
// 或者使用 DateTime (推薦)
$dt = new DateTime('now', new DateTimeZone('Asia/Shanghai'));
echo $dt->format('Y-m-d H:i:s');
// 用戶時區轉換
$userTz = new DateTimeZone('America/New_York');
$dt->setTimezone($userTz);
echo $dt->format('Y-m-d H:i:s');
?>
性能提示
- 高頻調用場景避免重複創建 DateTime 對象
- 格式化字符串定義為常量複用
- 大批量日期處理考慮使用
strftime() (C 層實現,但已棄用 PHP 8.1+)