Unix timestamps in JavaScript
Get the current epoch time and convert between timestamps and dates in JavaScript. Every snippet below is copy-ready.
// note
Date.now() is milliseconds; divide by 1000 for seconds.
now.js · current timestamp
const nowSeconds = Math.floor(Date.now() / 1000);
const nowMillis = Date.now();
console.log(nowSeconds, nowMillis);
timestamp → date
const ts = 1700000000; // seconds
const date = new Date(ts * 1000);
console.log(date.toISOString()); // 2023-11-14T22:13:20.000Z
date → timestamp
const date = new Date('2023-11-14T22:13:20Z');
const ts = Math.floor(date.getTime() / 1000);
// current epoch
— seconds since 1970-01-01T00:00:00Z.
Watch out for these
- Seconds vs milliseconds. An epoch value 13 digits long is milliseconds; 10 digits is seconds. Mixing them gives dates in 1970 or 55828.
- Local vs UTC. Format functions that default to the machine's timezone will silently differ between servers.
- Leap seconds. Unix time ignores them — the count is a simple 86,400 seconds per day.
Reference: https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date