Date.prototype.toUTCString() 將 Date 對象轉換為**字符串**,使用 **UTC (世界協調時間)** 並遵循 **RFC 7231 / HTTP 日期格式**。
dateObj.toUTCString()
無參數。
"Wdy, DD Mon YYYY HH:MM:SS GMT"
Wdy:星期縮寫 (Mon, Tue...)DD:兩位數日期Mon:月份縮寫 (Jan, Feb...)YYYY:四位年份HH:MM:SS:24小時制時間GMT:固定時區標識(即 UTC)const date = new Date(1993, 6, 28, 14, 39, 7); // 本地時間 1993-07-28 14:39:07
console.log(date.toUTCString());
// "Wed, 28 Jul 1993 06:39:07 GMT" (假設本地 UTC+8,UTC 時間減 8 小時)
console.log(new Date().toUTCString());
// "Tue, 15 Oct 2024 02:30:45 GMT"
| 方法 | 輸出示例 | 時區 | 格式標準 |
|---|---|---|---|
toString() | "Wed Jul 28 1993 14:39:07 GMT+0800" | 本地 | 瀏覽器實現 |
toUTCString() | "Wed, 28 Jul 1993 06:39:07 GMT" | **UTC** | **RFC 7231 (HTTP)** |
toISOString() | "1993-07-28T06:39:07.000Z" | UTC | **ISO 8601** (推薦存儲) |
toGMTString() | "Wed, 28 Jul 1993 06:39:07 GMT" | UTC | **已棄用**,同 toUTCString |
// 設置緩存過期時間:1小時後
const expires = new Date(Date.now() + 3600000).toUTCString();
res.setHeader('Expires', expires);
// "Tue, 15 Oct 2024 03:30:45 GMT"
// Last-Modified
res.setHeader('Last-Modified', fileStat.mtime.toUTCString());
document.cookie = `sessionId=abc123; expires=${new Date(Date.now() + 86400000).toUTCString()}; path=/`;
// expires=Tue, 16 Oct 2024 02:30:45 GMT
<pubDate>${new Date().toUTCString()}</pubDate>
// Tue, 15 Oct 2024 02:30:45 GMT
// 統一用 UTC 存儲、傳輸、日誌
function logEvent(event) {
console.log(JSON.stringify({
event,
timestamp: new Date().toUTCString() // 或 toISOString()
}));
}
// Date.parse() 可解析 RFC 7231 格式
const utcStr = 'Wed, 28 Jul 1993 06:39:07 GMT';
const timestamp = Date.parse(utcStr); // 743822347000
const date = new Date(utcStr); // 自動解析
console.log(date.toISOString()); // "1993-07-28T06:39:07.000Z"
toISOString()toGMTString() 同功能,**請勿使用**toISOString()(ISO 8601、含毫秒、更通用)toUTCString() 是 HTTP、Cookie、RSS 等**網絡標準協議要求的日期格式**。雖然現代應用多改用 ISO 8601 (toISOString()),但在處理舊系統集成、HTTP 頭構建、Cookie 設置時,它仍是不可替換的標準輸出方法。