TypeScript

Format Relative Time ("3 days ago")

admin by @admin ADMIN
1d ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Use the built-in Intl.RelativeTimeFormat to render "3 days ago" / "in 5 hours". Localized for free — pass any BCP 47 locale. No date library needed.
TypeScript
Raw
const RTF = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });

const STEPS: Array<[Intl.RelativeTimeFormatUnit, number]> = [
  ['year',   31_536_000_000],
  ['month',   2_592_000_000],
  ['week',      604_800_000],
  ['day',        86_400_000],
  ['hour',        3_600_000],
  ['minute',         60_000],
  ['second',          1_000],
];

export function timeAgo(when: Date | number | string): string {
  const target = typeof when === 'object' ? when.getTime() : new Date(when).getTime();
  const diff   = target - Date.now();
  const abs    = Math.abs(diff);
  for (const [unit, ms] of STEPS) {
    if (abs >= ms || unit === 'second') {
      return RTF.format(Math.round(diff / ms), unit);
    }
  }
  return 'now';
}

timeAgo(Date.now() - 60_000);     // 'yesterday' / '1 minute ago' depending on numeric mode
timeAgo(Date.now() + 86_400_000); // 'tomorrow'
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.