Sub topic 13
"3 Days Ago": Relative Times with Intl.RelativeTimeFormat
Feeds, comment threads, and notification lists usually say "5 minutes ago" or "yesterday" instead of printing a full timestamp. Intl.RelativeTimeFormat produces these phrases in any supported locale. It handles word order, plural forms, and special words like "tomorrow" or the German "vorgestern" (the day before yesterday).
This chapter assumes you know how to create Intl formatters and read resolvedOptions(). It also assumes you can subtract two Date objects to get a difference in milliseconds and that you understand how daylight saving time (DST) affects local-time arithmetic. Those topics were covered in earlier chapters.
The Working Model: You Supply the Number and the Unit
Intl.RelativeTimeFormat does not calculate anything from dates. It formats a pair made of a signed number and a unit:
- A negative value means the past:
-3, "day"becomes "3 days ago". - A positive value means the future:
2, "hour"becomes "in 2 hours". - The unit is one of
"year","quarter","month","week","day","hour","minute", or"second". Plural spellings such as"days"are also accepted.
Your code has to work out how far apart two moments are and which unit fits best. The formatter only turns that decision into localized text.
const rtf = new Intl.RelativeTimeFormat("en");
console.log(rtf.format(-3, "day")); // "3 days ago"
console.log(rtf.format(2, "hours")); // "in 2 hours"
console.log(rtf.format(1, "quarter")); // "in 1 quarter"
console.log(rtf.format(1.5, "hour")); // "in 1.5 hours"Fractional values are formatted as given. Most interfaces round to whole numbers before calling format.
Constructor Options
| Option | Values | Default | Effect |
|---|---|---|---|
| `numeric` | `"always"`, `"auto"` | `"always"` | `"auto"` uses words like "yesterday" and "now" when the locale has them |
| `style` | `"long"`, `"short"`, `"narrow"` | `"long"` | Controls how much the unit name is abbreviated |
| `localeMatcher` | `"best fit"`, `"lookup"` | `"best fit"` | The algorithm used to pick a supported locale |
numeric: "always" versus "auto"
With "always", every output contains a number. With "auto", the formatter uses a word or phrase wherever the locale's data defines one for that value.
const always = new Intl.RelativeTimeFormat("en", { numeric: "always" });
const auto = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
for (const [value, unit] of [[-1, "day"], [0, "day"], [1, "day"], [-1, "week"], [0, "second"]]) {
console.log(value, unit, "|", always.format(value, unit), "|", auto.format(value, unit));
}
// -1 day | 1 day ago | yesterday
// 0 day | in 0 days | today
// 1 day | in 1 day | tomorrow
// -1 week | 1 week ago | last week
// 0 second | in 0 seconds | nowLocales differ in which values have special words. German has words for two days away in both directions:
const de = new Intl.RelativeTimeFormat("de", { numeric: "auto" });
console.log(de.format(-2, "day")); // "vorgestern"
console.log(de.format(2, "day")); // "übermorgen"
const es = new Intl.RelativeTimeFormat("es", { numeric: "auto" });
console.log(es.format(-1, "day")); // "ayer"style
The style option shortens unit names. The exact abbreviations come from the locale data that ships with your runtime, so they can change between engine versions.
for (const style of ["long", "short", "narrow"]) {
const f = new Intl.RelativeTimeFormat("en", { style });
console.log(style, f.format(-3, "month"));
}
// e.g. long "3 months ago", short "3 mo. ago", narrow "3mo ago"Edge Cases in the Input
Zero and negative zero
JavaScript has both 0 and -0, and this formatter treats them differently. With numeric: "always", 0 gives "in 0 days" and -0 gives "0 days ago". If you compute Math.trunc(-0.4), you get -0, so a value just in the past stays in the past. With "auto", both values usually produce the same word, such as "today" or "now".
const f = new Intl.RelativeTimeFormat("en");
console.log(f.format(0, "day")); // "in 0 days"
console.log(f.format(-0, "day")); // "0 days ago"Errors
The formatter throws a RangeError for an unknown unit or a non-finite number. A NaN value often comes from an Invalid Date (a Date whose time value is NaN) upstream, so validate dates before you format them.
const f = new Intl.RelativeTimeFormat("en");
for (const args of [[1, "fortnight"], [NaN, "day"], [Infinity, "hour"]]) {
try {
f.format(...args);
} catch (e) {
console.log(args, e.name); // RangeError for each
}
}The units "millisecond" and "decade" are not supported either.
Choosing the Unit: A timeAgo Helper
The usual approach starts with the difference in milliseconds and walks from the largest unit down. It picks the first unit that the absolute difference reaches.
const DAY = 24 * 60 * 60 * 1000;
const UNITS = [
["year", 365 * DAY],
["month", 30 * DAY],
["week", 7 * DAY],
["day", DAY],
["hour", 60 * 60 * 1000],
["minute", 60 * 1000],
["second", 1000],
];
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
function timeAgo(date, now = new Date()) {
const diff = date.getTime() - now.getTime();
if (Number.isNaN(diff)) throw new RangeError("Invalid Date");
for (const [unit, ms] of UNITS) {
if (Math.abs(diff) >= ms || unit === "second") {
return rtf.format(Math.trunc(diff / ms), unit);
}
}
}
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-04T12:00:00Z"), now)); // "now"
console.log(timeAgo(new Date("2024-08-20T12:00:00Z"), now)); // "next month"
console.log(timeAgo(new Date("2023-06-01T12:00:00Z"), now)); // "last year"This helper makes some trade-offs you should know about:
- Approximate months and years. A month is treated as 30 days and a year as 365. That is fine for "about when" labels but wrong for billing or calendar logic.
- Truncation versus rounding.
Math.truncnever shows a value that belongs to the next unit up. WithMath.round, 59.6 minutes would print "60 minutes ago" instead of moving to hours. The cost is that 47 hours prints "yesterday". - Stale output. "now" stays on screen unchanged unless you re-render it. Refresh relative labels on a timer, or show the absolute time in a tooltip.
Elapsed Time versus Calendar Days
Suppose a message was sent at 23:00 and it is now 00:30 the next morning. Only 1.5 hours have passed, so timeAgo says "1 hour ago". A user reading "yesterday" would expect it here, because the message falls on the previous calendar day. That word answers a calendar question, not an elapsed-time question.
To answer it, compare local calendar dates. Moving each date's local year, month, and day into Date.UTC removes the time of day. It also removes any DST hour, so the division by one day comes out as a whole number.
function calendarDayDiff(date, now) {
const a = Date.UTC(date.getFullYear(), date.getMonth(), date.getDate());
const b = Date.UTC(now.getFullYear(), now.getMonth(), now.getDate());
return Math.round((a - b) / 86400000);
}
const auto = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
const sent = new Date(2024, 6, 3, 23, 0); // July 3, 23:00 local
const current = new Date(2024, 6, 4, 0, 30); // July 4, 00:30 local
console.log(auto.format(calendarDayDiff(sent, current), "day")); // "yesterday"A common design uses elapsed units below one day ("in 20 minutes", "3 hours ago") and calendar days beyond that ("yesterday", "3 days ago").
formatToParts and resolvedOptions
formatToParts returns the output as typed pieces. Numeric parts also carry the unit. You can use this to style the number differently from the surrounding text.
const f = new Intl.RelativeTimeFormat("en");
console.log(f.formatToParts(100, "day"));
// [
// { type: "literal", value: "in " },
// { type: "integer", value: "100", unit: "day" },
// { type: "literal", value: " days" }
// ]
const auto = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
console.log(auto.formatToParts(-1, "day")); // [{ type: "literal", value: "yesterday" }]When a word replaces the number, the result contains only a single literal part. Code that searches for an "integer" part must handle that case. Large numbers get locale grouping inside the integer parts: in English, 1000 becomes "1", a group separator, and "000".
resolvedOptions() reports the locale and settings that were actually chosen. Call it to confirm which locale you got, because an unsupported request falls back without any error.
const f = new Intl.RelativeTimeFormat(["xx-XX", "fr"], { style: "short" });
console.log(f.resolvedOptions());
// { locale: "fr", style: "short", numeric: "always", numberingSystem: "latn" }
console.log(f.format(-3, "day")); // "il y a 3 j"Exercise
With new Intl.RelativeTimeFormat("en") (default options), what do format(-1, "day") and format(0, "day") return, and what changes if you pass { numeric: "auto" }?
Show answer
With the default numeric: "always", they return "1 day ago" and "in 0 days". With numeric: "auto", they return "yesterday" and "today", because English defines words for those values.
Exercise
A log entry was created at 22:50 local time, and the page renders at 01:10 local time the next day. The timeAgo helper shows "2 hours ago", but the product team wants "yesterday". Why do the results differ, and what fixes it?
Show answer
timeAgo measures elapsed milliseconds, and 2 hours 20 minutes truncates to 2 hours. "Yesterday" is a calendar statement. Compute the difference between the local calendar dates, for example by passing each date's getFullYear, getMonth, and getDate to Date.UTC, subtracting, and dividing by 86400000. Then pass the result (-1) with unit "day" to a formatter created with numeric: "auto".
Exercise
Your code calls rtf.format(Math.trunc((date - now) / 3600000), "hour") and sometimes throws a RangeError. What is the likely cause?
Show answer
date is probably an Invalid Date, so the subtraction produces NaN, and format throws a RangeError for non-finite values. Check Number.isNaN(date.getTime()) before formatting.