Unix Timestamp & Epoch in JavaScript
Master Unix timestamp generation, parsing, conversion, and timezone formatting in modern JavaScript and Node.js.
A Unix timestamp represents the total number of elapsed seconds (or milliseconds) since the Unix Epoch: January 1, 1970, 00:00:00 UTC. In JavaScript, understanding the distinction between millisecond timestamps and second timestamps is critical for cross-platform API interop.
Quick Start#
In JavaScript, Date.now() returns the current timestamp in milliseconds:
Converting a Timestamp to an ISO 8601 String#
To convert a numeric timestamp back into an ISO 8601 human-readable date string, pass milliseconds to the Date constructor:
Parsing Dates into Unix Timestamps#
To convert human-readable date strings into timestamps:
Timezone Formatting with Intl.DateTimeFormat#
JavaScript Date instances are UTC internally. To render timestamps in specific timezones without third-party libraries (like Moment or date-fns), use the standard Intl.DateTimeFormat:
Seconds vs Milliseconds Detection#
APIs from Python, Go, and PHP typically provide 10-digit Unix timestamps (seconds), while JavaScript, Java, and MongoDB often use 13-digit millisecond timestamps:
Best Practices#
- Explicitly document unit (seconds vs ms): Always name variables
timestampSecondsortimestampMsto prevent 1000x scaling errors. - Always persist in UTC: Store UTC epoch timestamps in database columns to avoid timezone ambiguity.
- Use BigInt for microsecond/nanosecond timestamps: When interacting with low-level systems (such as high-precision trace IDs), use
process.hrtime.bigint()and JavaScriptBigInt.