Timestamp Converter — TypeScript source
Convert Unix epoch timestamps to human-readable dates and back. See seconds, milliseconds, ISO 8601, UTC, local and relative time at once.
This is the TypeScript implementation — the same logic the interactive tool runs, in a shareable, citable form.
// Pure surface of the timestamp tool (slug: timestamp). The island renders
// rows via locale-aware Date builtins; the genuinely portable logic is the
// human relative-time breakdown (thresholds, rounding, direction). `now` is
// injected so tests are deterministic; the thresholds mirror the island's
// original behavior exactly.
export type RelativeUnit = 'sec' | 'min' | 'hr' | 'day' | 'month' | 'yr';
export type RelativeDirection = 'past' | 'future';
export interface RelativeBreakdown {
/** Magnitude in `unit` (rounded). */
n: number;
unit: RelativeUnit;
direction: RelativeDirection;
}
const MIN = 60_000;
const HR = 3_600_000;
const DAY = 86_400_000;
const MONTH = DAY * 30;
const YEAR = DAY * 365;
/** Break |ms - now| into the coarsest unit under its threshold.
* 0 → { n: 0, unit: 'sec', direction: 'future' } ("in 0 sec"), matching the
* island's original rendering. */
export function relativeBreakdown(ms: number, now: number = Date.now()): RelativeBreakdown {
const diff = ms - now;
const abs = Math.abs(diff);
let n: number;
let unit: RelativeUnit;
if (abs < MIN) {
n = Math.round(abs / 1000);
unit = 'sec';
} else if (abs < HR) {
n = Math.round(abs / MIN);
unit = 'min';
} else if (abs < DAY) {
n = Math.round(abs / HR);
unit = 'hr';
} else if (abs < MONTH) {
n = Math.round(abs / DAY);
unit = 'day';
} else if (abs < YEAR) {
n = Math.round(abs / MONTH);
unit = 'month';
} else {
n = Math.round(abs / YEAR);
unit = 'yr';
}
return { n, unit, direction: diff < 0 ? 'past' : 'future' };
}
Also available in 13 other languages
Every CosmoDev tool ships its pure logic in TypeScript (web) and Go (CLI), with authored implementations in a dozen-plus languages — the same contract, ported. Compare all languages side by side →