Sub topic 13
"3 Days Ago": Relative Times with Intl.RelativeTimeFormat
This chapter assumes you know how to subtract two Date objects to get milliseconds, and how to create a formatter with a locale tag and an options object, as covered earlier in the tutorial.
Feeds, comments, and notifications often show times as "5 minutes ago" or "in 2 weeks" instead of a full date. Intl.RelativeTimeFormat produces these phrases in any locale. You supply two things: a signed number and a unit.
The Working Model
A relative time formatter does not compute anything from dates. It only turns (value, unit) into text:
- A negative value means the past:
-3, "day"gives "3 days ago". - A positive value means the future:
2, "week"gives "in 2 weeks". - Valid units are
"year","quarter","month","week","day","hour","minute", and"second". Plural spellings such as"days"are also accepted. Any other unit throws aRangeError.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
console.log(rtf.format(-1, "day")); // "yesterday"
console.log(rtf.format(1, "day")); // "tomorrow"
console.log(rtf.format(-3, "day")); // "3 days ago"
const always = new Intl.RelativeTimeFormat("en", { numeric: "always" });
console.log(always.format(-1, "day")); // "1 day ago"
const short = new Intl.RelativeTimeFormat("en", { style: "short" });
console.log(short.format(-3, "month")); // e.g. "3 mo. ago"
const es = new Intl.RelativeTimeFormat("es", { numeric: "auto" });
console.log(es.format(-1, "day")); // "ayer"The two options worth knowing are listed below.
| Option | Values | Effect |
|---|---|---|
| `numeric` | `"always"` (default), `"auto"` | `"auto"` uses words like "yesterday", "now", or "next week" where the locale has them |
| `style` | `"long"` (default), `"short"`, `"narrow"` | Controls how much the unit name is abbreviated |
From Two Dates to a Phrase
Your code has to pick the unit. A common approach starts with the difference in seconds and divides it up the unit ladder until the value is small enough for the current unit.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const DIVISIONS = [
{ amount: 60, unit: "second" },
{ amount: 60, unit: "minute" },
{ amount: 24, unit: "hour" },
{ amount: 7, unit: "day" },
{ amount: 4.34524, unit: "week" }, // average weeks per month
{ amount: 12, unit: "month" },
{ amount: Infinity, unit: "year" },
];
function timeAgo(date, now = new Date()) {
let duration = (date - now) / 1000; // negative when date is in the past
for (const { amount, unit } of DIVISIONS) {
if (Math.abs(duration) < amount) {
return rtf.format(Math.round(duration), unit);
}
duration /= amount;
}
}
const now = new Date("2024-07-04T12:00:00Z");
console.log(timeAgo(new Date("2024-07-01T12:00:00Z"), now)); // "3 days ago"
console.log(timeAgo(new Date("2024-07-04T11:15:00Z"), now)); // "45 minutes ago"
console.log(timeAgo(new Date("2024-07-11T12:00:00Z"), now)); // "next week"Common Errors
- Reversed sign. Computing
now - datemakes past events read as "in 3 days". Subtractnowfrom the event date. - Rounding at the boundary. The value 59.6 seconds passes the
< 60check and then rounds to 60, which prints "in 60 seconds". If that matters to you, round before you compare. - Months treated as exact. Months and years have different lengths. Dividing by averages is fine for "about 3 months ago", but use calendar arithmetic when you need exact counts.
- Making a formatter on every call. Create the formatter once at module level, as the helper above does.
Exercise
What do new Intl.RelativeTimeFormat("en", { numeric: "auto" }).format(0, "day") and the same call with numeric: "always" return?
Show answer
With "auto" it returns "today". With "always" it returns "in 0 days", because "always" never swaps in a word.
Exercise
An event happened 90 minutes before now. What does timeAgo return, and which unit does it pick?
Show answer
The difference is -5400 seconds. That becomes -90 minutes, which is not below 60, so it becomes -1.5 hours. That is below 24, and Math.round(-1.5) is -1, so the result is "1 hour ago" with the unit "hour".