在 JavaScript 中處理 Unix 時間戳
在 JavaScript 中處理 Unix 時間戳所需的一切 —— 取得當前時間、從時間戳建立 Date、為任意時區格式化,以及避免常見錯誤。
取得目前 Unix 時間戳
JavaScript 提供了幾種等價的方法來取得目前時間的數字時間戳。它們都回傳自 Unix 紀元以來的毫秒數。
- Date.now() → the fastest and most readable — 1700000000000 (milliseconds)
- Math.floor(Date.now() / 1000) → Unix timestamp in seconds — 1700000000
- +new Date() → same as Date.now(), using the unary plus operator
- new Date().getTime() → explicit method call, same result as Date.now()
從 Unix 時間戳建立 Date 物件
Date 建構函式接受自紀元以來的毫秒。把秒級時間戳傳給建構函式前,務必先乘以 1000。
- new Date(1700000000 * 1000) → from seconds (most common case)
- new Date(1700000000000) → from milliseconds (JavaScript APIs, Java)
- new Date(Date.now()) → current time as a Date object
- new Date(0) → the Unix epoch: January 1, 1970 00:00:00 UTC
格式化日期 — 內建字串方法
Date 物件有幾種內建的字串轉換方法,各自產生不同的格式。
- .toISOString() → '2023-11-15T06:13:20.000Z' — ISO 8601, always UTC, machine-readable
- .toUTCString() → 'Wed, 15 Nov 2023 06:13:20 GMT' — RFC 7231, human-readable UTC
- .toString() → local timezone string with full zone name
- .toLocaleString() → locale-aware format in the user's local timezone
用 Intl.DateTimeFormat 進行時區感知格式化
若要在不使用外部函式庫的情況下進行一致、時區感知的日期格式化,請使用 Intl.DateTimeFormat API。它在所有現代瀏覽器與 Node.js 13+ 中可用。
- new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York', dateStyle: 'full', timeStyle: 'long' }).format(date)
- date.toLocaleString('en-GB', { timeZone: 'Europe/London', hour12: false })
- new Intl.DateTimeFormat('zh-CN', { timeZone: 'Asia/Shanghai' }).format(date)
- new Intl.DateTimeFormat('en-CA', { timeZone: tz }).formatToParts(date) → array of {type, value} parts for custom layouts
將日期字串轉換回 Unix 時間戳
若要反向操作——從日期字串得到 Unix 時間戳——使用 Date.parse() 或把字串傳給 Date 建構函式。
- new Date('2023-11-15T06:13:20Z').getTime() / 1000 → Unix seconds from ISO 8601 UTC
- new Date('2023-11-15T01:13:20-05:00').getTime() → Unix milliseconds from ISO with offset
- Date.parse('2023-11-15T06:13:20Z') → same as new Date(...).getTime()
- Always use ISO 8601 format with explicit timezone for predictable parsing
常見陷阱
以下是 JavaScript 開發者在日期與時間戳上最常見的錯誤:
- new Date(1700000000) —— 漏乘 × 1000 會轉換成約 1970 年而非 2023 年
- getMonth() 回傳 0–11 而非 1–12 —— 顯示時務必加 1
- new Date('2024-01-01') 是 UTC 午夜;new Date('2024/01/01') 是本地午夜
- new Date(2024, 0, 1) = 1 月 1 日(建構函式中月份同樣從 0 開始)
- 用加 86400000ms 得到「明天」在日光節約時間邊界可能出錯 —— 改用 setDate(d.getDate() + 1)
JavaScript Unix 時間戳常見問題
- 在 JavaScript 中如何取得秒級 Unix 時間戳?
- 使用 Math.floor(Date.now() / 1000)。Date.now() 回傳毫秒,因此除以 1000 並向下取整即可得到整數的 Unix 秒。
- 為什麼用 Unix 時間戳呼叫 new Date() 會顯示 1970 年?
- Date 建構函式期望毫秒。10 位的秒級時間戳必須乘以 1000:new Date(seconds * 1000)。
- 如何為特定時區格式化 JavaScript 日期?
- 使用帶顯式 timeZone 選項的 Intl.DateTimeFormat,例如 new Intl.DateTimeFormat('en-US', { timeZone: 'America/New_York' })。它會自動套用日光節約時間,且無需外部函式庫。