JavaScript-Unix-Timestamp-Snippets
JavaScript-Beispiele zum Holen des aktuellen Timestamps, zum Umwandeln von Unix-Sekunden oder -Millisekunden in Date-Objekte und zum Formatieren der Ausgabe mit den eingebauten Browser-APIs.
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.