自 PHP 5.1.1 起,核心引入了一組預定義日期時間常量,涵蓋主流標準格式(ISO、RFC、RSS、ATOM 等)。直接配合 date()、DateTime::format() 使用,無需手寫複雜格式字符串,減少錯誤並提升代碼可讀性。
| 常量名 | 標準名稱 | 輸出示例 | 適用場景 |
|---|---|---|---|
DATE_ATOM | Atom (RFC 3339) | 2024-05-20T14:30:00+08:00 | Atom Feed、API 時間戳 |
DATE_COOKIE | HTTP Cookie | Monday, 20-May-2024 14:30:00 UTC | Cookie Expires 屬性 |
DATE_ISO8601 | ISO-8601 | 2024-05-20T14:30:00+0800 | 通用數據交換(注意:無冒號時區) |
DATE_RFC822 | RFC 822 | Mon, 20 May 2024 14:30:00 +0800 | 早期 Email 標頭 |
DATE_RFC850 | RFC 850 | Monday, 20-May-24 14:30:00 UTC | 舊版 HTTP/Email |
DATE_RFC1036 | RFC 1036 | Mon, 20 May 24 14:30:00 +0800 | Usenet/Email |
DATE_RFC1123 | RFC 1123 | Mon, 20 May 2024 14:30:00 +0800 | HTTP/1.1 Date 標頭(推薦) |
DATE_RFC2822 | RFC 2822 | Mon, 20 May 2024 14:30:00 +0800 | 現代 Email (RFC 5322 基礎) |
DATE_RFC3339 | RFC 3339 | 2024-05-20T14:30:00+08:00 | XML/JSON API、Atom(同 DATE_ATOM) |
DATE_RSS | RSS | Mon, 20 May 2024 14:30:00 +0800 | RSS 2.0 |
DATE_W3C | W3C | 2024-05-20T14:30:00+08:00 | HTML5 |
<?php
// 設置時區(必須)
date_default_timezone_set('Asia/Shanghai');
// 直接使用常量
$pubDate = date(DATE_RSS); // Mon, 20 May 2024 14:30:00 +0800
// 或使用 DateTime 物件(更現代、鏈式調用)
$dt = new DateTime();
$pubDate = $dt->format(DATE_RSS);
echo "<pubDate>$pubDate</pubDate>";
?>
function jsonResponse($data, $status = 200) {
http_response_code($status);
return json_encode([
'timestamp' => (new DateTime())->format(DATE_ATOM),
'data' => $data
], JSON_UNESCAPED_UNICODE | JSON_UNESCAPED_SLASHES);
}
$lastmod = (new DateTime($article->updated_at))->format(DATE_W3C);
// 輸出:2024-05-20T14:30:00+08:00
date_default_timezone_set() 會觸發 E_WARNING 並預設 UTCDATE_ISO8601 缺陷:輸出 +0800 無冒號,不符合嚴格 RFC 3339,**推薦改用 DATE_ATOM 或 DATE_RFC3339**DATE_RFC3339 常量,語義更明確DateTimeImmutable 避免狀態修改副作用項目中可定義業務專用常量,統一維護:
// config/constants.php
define('DATE_API_STANDARD', DATE_ATOM); // API 統一格式
define('DATE_LOG_FILE', 'Y-m-d H:i:s.u'); // 日誌高精度
define('DATE_UI_DISPLAY', 'Y年m月d日 H:i'); // 前端展示
最佳實踐:優先使用內建常量而非魔術字符串;統一時區管理;API 輸出採用
DATE_ATOM/DATE_RFC3339;日誌記錄可自定義高精度格式。