JavaScript Snippets

JavaScript Unix Timestamp Snippets

JavaScript examples for getting the current timestamp, converting Unix seconds or milliseconds to Date objects, and formatting output with built-in browser APIs.

Current Unix timestamp (seconds)
Math.floor(Date.now() / 1000)
Current Unix timestamp (milliseconds)
Date.now()
Timestamp from a Date object
new Date().getTime()
// or
+new Date()
Date object from Unix timestamp (seconds)
new Date(1700000000 * 1000)
ISO 8601 string from timestamp
new Date(1700000000 * 1000).toISOString()
// → "2023-11-15T06:13:20.000Z"
Formatted local string
new Date(1700000000 * 1000).toLocaleString()
new Date(1700000000 * 1000).toLocaleString("en-US", { timeZone: "America/New_York" })

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

Related JavaScript references

FAQ

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.