萬盛學電腦網

您现在的位置: 萬盛學電腦網 >> 程式設計 >  >> 腳本程式專題 >> JavaScript

JavaScript Date.UTC() 方法:構建 UTC 時間戳

Date.UTC() 方法簡介

Date.UTC() 靜態方法接受**日期時間分量**(年、月、日、時、分、秒、毫秒),返回**自 UTC 1970-01-01 00:00:00 以來的毫秒數**(UTC 時間戳)。

語法

Date.UTC(year, monthIndex[, day[, hours[, minutes[, seconds[, ms]]]]])

參數詳解

參數範圍說明
year四位數 (如 2024)**必填**。兩位數會被視為 1900+ (如 98→1998),避免使用
monthIndex0-11**必填**。**0=一月,11=十二月**(關鍵:月份 0 基)
day1-31可選,默認 1
hours0-23可選,默認 0
minutes0-59可選,默認 0
seconds0-59可選,默認 0
ms0-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() vs new Date() 關鍵區別

特性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)

核心應用場景

1. 構建固定 UTC 時間點(跨時區一致)

// 系統維護窗口:每天 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;
}

2. 日期數學運算基準

// 計算某年某月天數
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

3. 避免時區偏移導致的日期跳變

// ❌ 危險:本地構造可能因時區導致日期偏移
new Date(2024, 9, 15).getDate(); // 在 UTC-12 可能是 14號

// ✅ 安全:UTC 構造再取日期
new Date(Date.UTC(2024, 9, 15)).getUTCDate(); // 永遠 15

注意事項

  • 月份 0-11:最常見 Bug 來源,寫註釋或封裝 utcDate(year, month1to12, ...)
  • 年份四位數:避免兩位數歧義
  • 返回值是 Number:需 new Date(ms) 轉對象
  • 參數超範圍自動進位:可用於日期運算技巧(如上例求月天數)

現代替代:Temporal API (提案階段)

// 未來標準:更清晰、不可變、時區感知
// 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() 的時區差異,是處理跨時區業務(全球化應用、定時任務、日誌系統)的關鍵。

copyright © 萬盛學電腦網 all rights reserved