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.

Emit the unit the consumer expectsSending ms where seconds are wantedEmit the unit the consumer expectsdate.getTime() as seconds1000x too largefloor(getTime()/1000)whole secondsgetTime is milliseconds; floor-divide by 1000 for seconds.

Minimal working solution

const date = new Date('2024-03-15T14:30:00Z');
const ms = date.getTime();                 // 1710513000000
const seconds = Math.floor(ms / 1000);     // 1710513000

Date to secondsgetTime then floor-divide by 1000Date to secondsDategetTime()/1000 floorseconds

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) };
}

From a Temporal.InstantepochMilliseconds names the unitFrom a Temporal.InstantInstantepochMs/1000{ms,seconds}

Verification snippet

Date to Unix Timestamp assertionsKey cases assert correctlyAssertions that prove the edge casegetTime()1710513000000 msfloor(/1000)1710513000 sfractional mstruncatedInstant.epochMillisecondssame ms

Common pitfalls

Date to Unix Timestamp pitfallsCommon mistakes and their fixesWrongRightsend getTime() as seconds1000x offfloor(getTime()/1000)secondsround instead of floorovershoots by a secondname the unitno mixups

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.