Unix timestamps in TypeScript
Get the current epoch time and convert between timestamps and dates in TypeScript. Every snippet below is copy-ready.
// note
Same runtime as JavaScript, with explicit types on the boundaries.
now.ts · current timestamp
const nowSeconds: number = Math.floor(Date.now() / 1000);
const nowMillis: number = Date.now();
timestamp → date
const ts: number = 1700000000;
const date: Date = new Date(ts * 1000);
console.log(date.toISOString());
date → timestamp
const ts: number = Math.floor(
new Date('2023-11-14T22:13:20Z').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://www.typescriptlang.org/docs/handbook/2/everyday-types.html