Convert a Date to a Unix Timestamp in JavaScript
To convert a Date to a Unix timestamp in seconds, use Math.floor(date.getTime() / 1000); getTime() alone gives milliseconds. Part of Unix Timestamps & Epoch Conversion.
Why this scenario is tricky
getTime() (or +date) already gives epoch milliseconds — the value most JavaScript APIs want. The only real work is emitting seconds for systems that expect them, and doing the division with Math.floor so a fractional second is truncated rather than rounded up into the next second.
Minimal working solution
const date = new Date('2024-03-15T14:30:00Z');
const ms = date.getTime(); // 1710513000000
const seconds = Math.floor(ms / 1000); // 1710513000
Full production version
import { Temporal } from '@js-temporal/polyfill';
// From a Temporal.Instant, the units are explicit.
function toEpoch(i: Temporal.Instant) {
return { ms: i.epochMilliseconds, seconds: Math.floor(i.epochMilliseconds / 1000) };
}
Verification snippet
Common pitfalls
Frequently Asked Questions
How do I convert a Date to a Unix timestamp?
Call date.getTime() for milliseconds, or Math.floor(date.getTime() / 1000) for the whole-second Unix timestamp most backends and JWTs use. Flooring rather than rounding avoids overshooting into the next second.
Is getTime() in seconds or milliseconds?
Milliseconds. JavaScript works in epoch milliseconds throughout, so getTime(), Date.now(), and Temporal.Instant.epochMilliseconds are all millisecond values; divide by 1000 when a system expects seconds.