在 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' })。它会自动应用夏令时,且无需外部库。