toUTCString() 方法將 Date 物件轉為 UTC (世界協調時間) 字串,格式符合 RFC 7231 標準 (如 "Mon, 15 Jan 2024 08:30:00 GMT")。常用於 HTTP 標頭、Cookie 過期時間、跨時區時間紀錄。
dateObj.toUTCString()
"Www, DD Mmm YYYY HH:MM:SS GMT"。const now = new Date();
console.log(now.toUTCString());
// 輸出範例: "Mon, 15 Jan 2024 08:30:45 GMT"
<!DOCTYPE html>
<html>
<head>
<meta charset="utf-8">
<title>UTC 時間顯示</title>
</head>
<body>
<p id="demo">點擊按鈕顯示 UTC 時間</p>
<button onclick="showUTC()">顯示 UTC</button>
<script>
function showUTC() {
const d = new Date();
document.getElementById('demo').innerHTML = d.toUTCString();
}
</script>
</body>
</html>
function setCookie(name, value, days) {
const expires = new Date(Date.now() + days * 864e5).toUTCString();
document.cookie = `${name}=${value}; expires=${expires}; path=/`;
}
setCookie('token', 'abc123', 7); // 7 天后過期
| 需求 | 方法 | 說明 |
|---|---|---|
| 取得 UTC 字串 | toUTCString() | 標準格式字串 |
| 取得 UTC 時間戳 | getTime() / valueOf() | 毫秒數 (自 1970) |
| 取得 UTC 年/月/日 | getUTCFullYear() 等 | 對應 UTC 數值 |
| 建立 UTC 日期 | Date.UTC() | 回傳時間戳 |
| 本地轉 UTC 字串 | new Date(local).toUTCString() | 自動換算 |
toUTCString() 只回傳字串,不改變物件內部時間值。getUTC* 方法或使用 Intl.DateTimeFormat。GMT 結尾,實際等同 UTC。const fmt = new Intl.DateTimeFormat('en-US', {
timeZone: 'UTC',
weekday: 'short', year: 'numeric', month: 'short', day: '2-digit',
hour: '2-digit', minute: '2-digit', second: '2-digit',
hour12: false
});
console.log(fmt.format(new Date()).replace(',', '') + ' GMT');
// 輸出格式相近,但可自訂區域與格式
toUTCString() 提供標準、可讀性高的 UTC 時間字串,適用於網路協定、跨時區記錄。若需更靈活格式,請改用 Intl.DateTimeFormat 或手動組合 UTC 取值方法。