JavaScript Unix 时间戳代码片段

JavaScript 示例,用于获取当前时间戳、将 Unix 秒或毫秒转换为 Date 对象,以及用浏览器内置 API 格式化输出。

JavaScript timestamp basics

JavaScript Date stores time as milliseconds since the Unix epoch. Use Date.now() when you need milliseconds and Math.floor(Date.now() / 1000) when an API expects Unix seconds.

Common JavaScript conversions

When converting a Unix timestamp in seconds to a Date, multiply by 1000 before calling new Date(). Use toISOString() for UTC output, toUTCString() for HTTP-style output, and Intl.DateTimeFormat when you need a specific timezone.

JavaScript production notes

JavaScript timestamp bugs usually come from mixing Date milliseconds with API seconds. Keep Date objects at the edge of the UI, and pass plain numbers or ISO strings through APIs only after the unit is explicit. When displaying local time, use Intl.DateTimeFormat with a named timezone so the result is repeatable across browsers and servers.

  • Use Date.now() when you need epoch milliseconds for timers, analytics events, or browser storage
  • Use Math.floor(Date.now() / 1000) when a backend endpoint expects Unix seconds
  • Use new Date(seconds * 1000) when an API sends seconds
  • Use toISOString() for UTC strings that can round-trip through JSON

Frequently checked JavaScript details

Does Date.now() return Unix seconds?
No. Date.now() returns milliseconds. Divide by 1000 and round down when an API, database, or command-line tool expects Unix seconds.
Should I store Date objects in JSON?
No. Convert the value to a number or an ISO 8601 string first. JSON has no native Date type, so explicit values are easier to debug and compare.