萬盛學電腦網

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

JavaScript Date 對象完全指南:構造、方法、時區陷阱與最佳實踐

Date 構造函數全解析


// 1. 無參數:當前時間
new Date() // 2024-01-15T06:30:45.123Z

// 2. 時間戳(毫秒)
new Date(1705300245123) // 2024-01-15T06:30:45.123Z

// 3. 日期字符串(ISO 8601 推薦)
new Date('2024-01-15')           // 本地時間 2024-01-15 00:00:00
new Date('2024-01-15T14:30:45')  // 本地時間
new Date('2024-01-15T14:30:45Z') // UTC 時間
new Date('2024/01/15 14:30:45')  // 非標準,瀏覽器解析不一

// 4. 分量構造(關鍵:月份 0-11)
new Date(2024, 0, 15)           // 2024-01-15 00:00:00 本地時間
new Date(2024, 0, 15, 14, 30, 45, 123) // 完整分量
// ⚠️ 陷阱:month=12 會自動進位到明年 1 月
new Date(2024, 12, 1) // 2025-01-01 (不是 2024-12-01)

月份陷阱深度解析


// 錯誤示範
const date = new Date(2024, 12, 25); // 認為是 12 月
console.log(date.getMonth()); // 0 (實際是 2025 年 1 月)

// 正確寫法
const date = new Date(2024, 11, 25); // 月份 -1
console.log(date.getMonth()); // 11
console.log(date.getMonth() + 1); // 12 ✓

// 封裝安全構造函數
function createDate(year, month1to12, day, hour=0, min=0, sec=0, ms=0) {
  return new Date(year, month1to12 - 1, day, hour, min, sec, ms);
}

createDate(2024, 12, 25); // 正確得到 2024-12-25

核心方法分類

類別方法返回值備註
獲取 (本地)getFullYear()年 (4位)替代 getYear()
getMonth()月 (0-11)+1 顯示
getDate()日 (1-31)
getDay()星期 (0-6)0=周日
getHours()時 (0-23)
getMinutes()分 (0-59)
getSeconds()秒 (0-59)
getMilliseconds()毫秒 (0-999)
獲取 (UTC)getUTCFullYear()UTC 年
getUTCMonth()UTC 月 (0-11)
getUTCDate()UTC 日
getUTCDay()UTC 星期
getUTCHours()UTC 時
getUTCMinutes()UTC 分
getUTCSeconds()UTC 秒
getUTCMilliseconds()UTC 毫秒
設置 (本地)setFullYear(y)時間戳自動進位
setMonth(m)時間戳0-11,自動進位
setDate(d)時間戳1-31,自動進位
setHours(h,m,s,ms)時間戳
設置 (UTC)setUTCFullYear...時間戳UTC 設置
... (類似以上)
時間戳getTime() / valueOf()毫秒數 (從 1970-01-01 UTC)Number(date) 同義
字符串toISOString()ISO 8601 UTC"2024-01-15T06:30:45.123Z"
toLocaleString()本地化字符串受瀏覽器語言影響
toDateString()日期部分"Mon Jan 15 2024"
toTimeString()時間部分"14:30:45 GMT+0800"
靜態Date.now()當前時間戳等價 +new Date()
Date.parse(str)解析字符串得時間戳不推薦,解析不一致
Date.UTC(y,m,d...)UTC 時間戳月 0-11

時區處理核心


// 獲取時區偏移(分鐘,東區負,西區正)
const offset = new Date().getTimezoneOffset(); // 東八區 = -480

// 手動構造指定時區時間
function createDateInTZ(year, month, day, hour, minute, tzOffsetHours = 8) {
  // tzOffsetHours: 目標時區相對 UTC 偏移(東八區=8)
  const utcMs = Date.UTC(year, month - 1, day, hour - tzOffsetHours, minute);
  return new Date(utcMs);
}

// 格式化為指定時區(利用 Intl)
function formatInTZ(date, tz = 'Asia/Shanghai', fmt = 'yyyy-MM-dd HH:mm:ss') {
  return new Intl.DateTimeFormat('zh-CN', {
    timeZone: tz,
    year: 'numeric', month: '2-digit', day: '2-digit',
    hour: '2-digit', minute: '2-digit', second: '2-digit',
    hour12: false
  }).format(date).replace(/\//g, '-');
}

formatInTZ(new Date(), 'America/New_York'); // 紐約時間

日期運算工具函數


const DateUtils = {
  // 添加天數(自動處理月份/年份進位)
  addDays(date, days) {
    const d = new Date(date);
    d.setDate(d.getDate() + days);
    return d;
  },
  
  // 添加月份
  addMonths(date, months) {
    const d = new Date(date);
    const day = d.getDate();
    d.setMonth(d.getMonth() + months);
    // 處理 31號 到 30天月份 的回退問題
    if (d.getDate() !== day) d.setDate(0); // 設置為上月最後一天
    return d;
  },
  
  // 當月天數
  daysInMonth(year, month1to12) {
    return new Date(year, month1to12, 0).getDate();
  },
  
  // 是否閏年
  isLeapYear(year) {
    return (year % 4 === 0 && year % 100 !== 0) || year % 400 === 0;
  },
  
  // 日期差(天)
  diffDays(date1, date2) {
    const d1 = new Date(date1).setHours(0,0,0,0);
    const d2 = new Date(date2).setHours(0,0,0,0);
    return Math.round((d2 - d1) / 86400000);
  },
  
  // 週幾 (0-6, 0=周日)
  getDay(date) {
    return new Date(date).getDay();
  },
  
  // 格式化(調用前文 formatDate)
  format: formatDate
};

現代替代:Temporal API (Stage 3 提案)


// 未來標準,解決 Date 所有痛點
// import { Temporal } from '@js-temporal/polyfill'; // 當前需 polyfill

const date = Temporal.PlainDate.from('2024-01-15');
const dateTime = Temporal.PlainDateTime.from('2024-01-15T14:30:45');
const zoned = Temporal.ZonedDateTime.from('2024-01-15T14:30:45+08:00[Asia/Shanghai]');

date.add({ months: 1 }); // 2024-02-15 (不可變)
zoned.withTimeZone('America/New_York'); // 時區轉換
zoned.toPlainDate(); // 日期部分

最佳實踐清單

  1. 存儲/傳輸用 ISO 8601 (UTC): toISOString(),數據庫存 TIMESTAMP WITH TIME ZONE
  2. 展示用本地/用戶時區: Intl.DateTimeFormat 或 formatDate 配合 timeZone
  3. 構造日期用分量形式: new Date(year, month-1, day) 避免字符串解析歧義
  4. 月份永遠 -1: 封裝 createDate(y, m, d) 統一入口
  5. 日期運算用工具函數: 手動加減毫秒易出錯(夏令時、閏秒)
  6. 避免 new Date() 在循環/高頻調用: 緩存當前時間基準
copyright © 萬盛學電腦網 all rights reserved