Date.UTC() 靜態方法接受**日期時間分量**(年、月、日、時、分、秒、毫秒),返回**自 UTC 1970-01-01 00:00:00 以來的毫秒數**(UTC 時間戳)。
Date.UTC(year, monthIndex[, day[, hours[, minutes[, seconds[, ms]]]]])
| 參數 | 範圍 | 說明 |
|---|---|---|
year | 四位數 (如 2024) | **必填**。兩位數會被視為 1900+ (如 98→1998),避免使用 |
monthIndex | 0-11 | **必填**。**0=一月,11=十二月**(關鍵:月份 0 基) |
day | 1-31 | 可選,默認 1 |
hours | 0-23 | 可選,默認 0 |
minutes | 0-59 | 可選,默認 0 |
seconds | 0-59 | 可選,默認 0 |
ms | 0-999 | 可選,默認 0 |
// 基礎:2024-10-15 10:30:45 UTC
const timestamp = Date.UTC(2024, 9, 15, 10, 30, 45); // 月份 9 = 10月
console.log(timestamp); // 1728988245000
// 構造 UTC Date 對象
const date = new Date(Date.UTC(2024, 9, 15, 10, 30, 45));
console.log(date.toISOString()); // "2024-10-15T10:30:45.000Z"
// 參數溢出自動進位
console.log(Date.UTC(2024, 12, 1)); // 2025-01-01 (月份 12 → 翌年 1月)
console.log(Date.UTC(2024, 9, 32)); // 2024-11-01 (日期 32 → 11月1日)
| 特性 | Date.UTC() | new Date(year, month...) |
|---|---|---|
| 返回值 | 毫秒數 | Date 對象 |
| 時區 | **UTC** | **本地時區** |
| 月份基數 | 0-11 (同) | 0-11 (同) |
| 參數解釋 | 視為 UTC 時間分量 | 視為本地時間分量 |
// 同一組參數,結果不同(取決於本地時區)
const utcMs = Date.UTC(2024, 9, 15, 10, 30); // UTC 10:30
const localDate = new Date(2024, 9, 15, 10, 30); // 本地 10:30
console.log(new Date(utcMs).toISOString()); // "2024-10-15T10:30:00.000Z"
console.log(localDate.toISOString()); // "2024-10-15T02:30:00.000Z" (假設 UTC+8)
// 系統維護窗口:每天 UTC 04:00-05:00
const maintenanceStart = Date.UTC(2024, 9, 15, 4, 0);
const maintenanceEnd = Date.UTC(2024, 9, 15, 5, 0);
function isMaintenanceWindow() {
const now = Date.now();
return now >= maintenanceStart && now < maintenanceEnd;
}
// 計算某年某月天數
function daysInMonth(year, month) { // month 1-12
// 下月 1 日 的 UTC 0點 減 1 毫秒 = 本月最後一天 23:59:59.999
return new Date(Date.UTC(year, month, 1, 0, 0, 0, -1)).getUTCDate();
}
console.log(daysInMonth(2024, 2)); // 29 (閏年)
console.log(daysInMonth(2023, 2)); // 28
// ❌ 危險:本地構造可能因時區導致日期偏移
new Date(2024, 9, 15).getDate(); // 在 UTC-12 可能是 14號
// ✅ 安全:UTC 構造再取日期
new Date(Date.UTC(2024, 9, 15)).getUTCDate(); // 永遠 15
utcDate(year, month1to12, ...)new Date(ms) 轉對象// 未來標準:更清晰、不可變、時區感知
// import { PlainDateTime, TimeZone } from '@js-temporal/polyfill';
const dt = PlainDateTime.from('2024-10-15T10:30:45').withTimeZone('UTC');
const instant = dt.toInstant(); // 精確時間點
Date.UTC() 是構建**時區無關**時間戳的基石。理解其與 new Date() 的時區差異,是處理跨時區業務(全球化應用、定時任務、日誌系統)的關鍵。