typescript 27 lines · 7 steps

Human-readable relative times with Intl

Convert a timestamp into phrases like "3 days ago" by walking through escalating time units.

Explained by highlit
1const DIVISIONS: { amount: number; unit: Intl.RelativeTimeFormatUnit }[] = [
2 { amount: 60, unit: "seconds" },
3 { amount: 60, unit: "minutes" },
4 { amount: 24, unit: "hours" },
5 { amount: 7, unit: "days" },
6 { amount: 4.34524, unit: "weeks" },
7 { amount: 12, unit: "months" },
8 { amount: Number.POSITIVE_INFINITY, unit: "years" },
9];
10 
11export function formatRelativeTime(
12 date: Date | number | string,
13 locale = "en-US",
14): string {
15 const formatter = new Intl.RelativeTimeFormat(locale, { numeric: "auto" });
16 const target = date instanceof Date ? date : new Date(date);
17 let duration = (target.getTime() - Date.now()) / 1000;
18 
19 for (const { amount, unit } of DIVISIONS) {
20 if (Math.abs(duration) < amount) {
21 return formatter.format(Math.round(duration), unit);
22 }
23 duration /= amount;
24 }
25 
26 return formatter.format(Math.round(duration), "years");
27}
01 / 01
STEP 01

Walkthrough

Space play step click any line
Three takeaways
  1. 1A table of unit thresholds turns repetitive time math into a single clean loop.
  2. 2Intl.RelativeTimeFormat handles localization and natural phrasing so you never hardcode strings.
  3. 3Dividing the running duration by each unit's size lets one pass scale from seconds up to years.

Related explainers

Share this explainer

Here's the card — post it anywhere.

Human-readable relative times with Intl — share card
Made with highlit — turn any snippet into a walkthrough like this in about a minute.
Explain your code