Unix Timestamp in TypeScript
TypeScript uses the same Date API as JavaScript but adds static typing. Adding explicit type annotations prevents common timestamp bugs — like accidentally mixing seconds and milliseconds — at compile time.
Code Examples
Current timestamp (seconds)
const seconds: number = Math.floor(Date.now() / 1000);
Type-annotated Unix timestamp in seconds. The number type annotation is optional but makes the intent explicit — this is seconds, not milliseconds.
Current timestamp (milliseconds)
const ms: number = Date.now();
Date.now() natively returns a number in milliseconds. In TypeScript, this is typed as number. A 13-digit value.
Branded types — prevent seconds/ms confusion
type Seconds = number & { readonly __brand: "seconds" };
type Milliseconds = number & { readonly __brand: "milliseconds" };
const toSeconds = (ms: Milliseconds): Seconds =>
Math.floor(ms / 1000) as Seconds;
const now: Milliseconds = Date.now() as Milliseconds;
const nowSeconds: Seconds = toSeconds(now);Advanced pattern: branded (nominal) types ensure you can't accidentally pass milliseconds where seconds are expected. The TypeScript compiler will error if you mix them.
Convert Date string to timestamp
const ts: number = Math.floor(new Date("2024-06-15T12:00:00Z").getTime() / 1000);Parse an ISO 8601 string and convert to Unix seconds. getTime() returns milliseconds, so divide by 1000.
Convert timestamp to Date
const date: Date = new Date(seconds * 1000); const iso: string = date.toISOString();
Multiply seconds by 1000 to get milliseconds before passing to the Date constructor. toISOString() returns a UTC string like 2024-02-22T00:00:00.000Z.
Note
TypeScript's number type doesn't distinguish between seconds and milliseconds — both are just number. The branded type pattern above is an advanced but powerful technique for preventing this class of bug in large codebases. For simpler code, a naming convention (tsSeconds, tsMs) is usually sufficient.
Need to convert a specific timestamp? Use the live converter — paste any epoch value and see the human-readable date instantly.
← Open the converter