staging-org / ocean-landing-serve / src/ lib/ time.ts

const relative = new Intl.RelativeTimeFormat('en-US', { numeric: 'auto' });
const steps: [Intl.RelativeTimeFormatUnit, number][] = [
	['day', 86_400_000],
	['hour', 3_600_000],
	['minute', 60_000]
];

export const ago = (iso: string, now = Date.now()) => {
	const diff = new Date(iso).getTime() - now;
	// A timestamp a little ahead of this machine's clock is skew, not the future.
	if (diff > 0) return 'just now';
	for (const [unit, ms] of steps) if (Math.abs(diff) >= ms) return relative.format(Math.round(diff / ms), unit);
	return 'just now';
};