Get the Current Unix Timestamp in JavaScript
To get the current Unix timestamp in seconds, use Math.floor(Date.now() / 1000); Date.now() alone gives milliseconds. Part of Unix Timestamps & Epoch Conversion.
Why this scenario is tricky
JavaScript counts the epoch in milliseconds, but Unix time, database epoch functions, and JWT exp/iat claims count whole seconds. Emit the milliseconds where a millisecond value is expected and the seconds where seconds are — mixing them puts a token's expiry a thousand-fold too far in the future.
Minimal working solution
const ms = Date.now(); // 1710513000123 (milliseconds)
const seconds = Math.floor(ms / 1000); // 1710513000 (whole seconds)
Full production version
// Name the unit so callers cannot mix them up.
export const nowMs = () => Date.now();
export const nowSeconds = () => Math.floor(Date.now() / 1000);
export const nowInstant = () => nowMs(); // pass ms to new Date()
Verification snippet
Common pitfalls
Frequently Asked Questions
How do I get the current Unix timestamp in seconds?
Use Math.floor(Date.now() / 1000). Date.now() returns milliseconds since the epoch, and Unix time is measured in whole seconds, so you divide by 1000 and floor to drop the millisecond remainder.
Why does my JWT expire immediately or never?
You likely passed Date.now() (milliseconds) where the exp claim expects seconds, or vice versa. JWT exp and iat are Unix seconds, so use Math.floor(Date.now() / 1000) when signing and compare against seconds when validating.