Format relative time from a date with JavaScript Intl
How to turn a Date into localized phrases like "3 days ago" with Intl.RelativeTimeFormat, what the conversion changes, and when an absolute date is the safer choice.
Intl.RelativeTimeFormat turns a number and a unit into a localized phrase such as "3 days ago" or "in 2 weeks". It does not accept a Date object. To format relative time from a date, you calculate the difference between that date and the current moment, choose a unit, and pass both to the formatter. This review covers what that conversion changes, where it works well, and where a plain absolute date is the better choice.
Short verdict: when relative time is the right fit
Relative time suits interfaces where recency matters more than the exact moment, such as activity feeds, comment threads, notifications and "last updated" labels. Its main benefit is that the runtime handles localized grammar, plural rules and natural phrases like "yesterday" or "next month", so you do not maintain translation strings for every unit and count. The decisive tradeoff is that the phrase is only accurate at the moment it is rendered, and it gives up precision. Use an absolute date instead, or show both, for deadlines, schedules, legal or financial records, audit logs, and any text that is likely to be copied, exported, printed, emailed or cached.
What Intl.RelativeTimeFormat does and does not do
The constructor takes a locale (or list of locales) and an options object. The formatter itself is stateless with respect to time: it never reads the clock and knows nothing about the date you started from. It only phrases the value and unit you give it.
- numeric: "always" (default) always uses a number, giving "1 day ago"; "auto" allows idiomatic phrases such as "yesterday", "today" or "next week" where the locale defines them.
- style: "long" (default), "short" or "narrow" controls how abbreviated the unit wording is; the exact abbreviations depend on the locale.
- localeMatcher: "best fit" (default) or "lookup" controls how the requested locale is matched to available locale data.
The format method takes a value and one of these units: year, quarter, month, week, day, hour, minute or second (plural forms such as "days" are also accepted). A negative value means the past and a positive value means the future. There is also formatToParts, which returns the phrase split into literal and numeric pieces, useful if you want to style the number separately without parsing the string.
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
rtf.format(-1, 'day'); // "yesterday"
rtf.format(0, 'day'); // "today"
rtf.format(2, 'week'); // "in 2 weeks"
const always = new Intl.RelativeTimeFormat('en', { numeric: 'always' });
always.format(-1, 'day'); // "1 day ago"
Converting a Date into a value and unit
A common approach is to take the millisecond difference between the target date and now, then step up through units until the magnitude is small enough for the current one. The helper below follows that pattern.
const DIVISIONS = [
{ amount: 60, unit: 'second' },
{ amount: 60, unit: 'minute' },
{ amount: 24, unit: 'hour' },
{ amount: 7, unit: 'day' },
{ amount: 4.34524, unit: 'week' },
{ amount: 12, unit: 'month' },
{ amount: Infinity, unit: 'year' },
];
function formatRelative(date, now = new Date(), locale = undefined) {
const rtf = new Intl.RelativeTimeFormat(locale, { numeric: 'auto' });
let duration = (date.getTime() - now.getTime()) / 1000;
for (const { amount, unit } of DIVISIONS) {
if (Math.abs(duration) < amount) {
return rtf.format(Math.round(duration), unit);
}
duration /= amount;
}
}
Subtracting now from the target date makes past dates negative and future dates positive, which matches what format expects. Passing undefined as the locale uses the runtime's default locale. The divisors for weeks into months and months into years are averages, so this helper is a readable approximation rather than calendar arithmetic.
- Months and years are approximate: a fixed weeks-per-month divisor can disagree with the calendar near month boundaries.
- "Yesterday" means a value of -1 days, not the previous calendar day. Something 30 hours ago rounds to -1 day and reads "yesterday" even if it happened two calendar days back; something 20 hours ago reads "20 hours ago" even if it was before midnight.
- Rounding can produce awkward boundary results, such as 59.6 seconds rounding to "60 seconds" instead of moving to minutes. Round before comparing against the threshold if that matters.
- The millisecond difference is time-zone independent, but any calendar-day logic you add depends on which time zone you evaluate dates in.
- An invalid Date yields NaN, and format throws a RangeError for non-finite values, so validate input first.
If labels like "yesterday" must match the calendar, compare calendar dates in the reader's time zone to get the day difference, then pass that whole number to format with the day unit. Where the Temporal API is available in your target runtimes, its calendar-aware date differences can replace the fixed divisors; check support before depending on it.
What the conversion actually changes
Formatting produces a new string. The underlying Date or timestamp is not modified, and nothing about the conversion is a visual effect: unlike CSS styling or presentational tricks, the output is real characters that will be copied, indexed and read aloud as written. The practical rule is to store the timestamp itself, ideally as a UTC instant or an ISO 8601 string, and generate the relative phrase only at display time. Storing the phrase discards the information needed to regenerate it later.
Nothing is reversed or mirrored here. For right-to-left locales such as Arabic or Hebrew, the output is stored in normal logical order, and the right-to-left reading direction comes from bidirectional display rules in the rendering environment, not from any change to the characters.
Readability after copying, sharing and assistive technology
Because the output is ordinary text, it copies and pastes cleanly. The problem is meaning, not encoding: "posted 2 hours ago" pasted into an email or document is wrong by the next day, and the reader has no way to recover the original time. Whenever content is likely to leave the page, include the absolute date in the visible text alongside the relative phrase.
Screen readers read the visible phrase like any other text. The datetime attribute on a time element is machine-readable, but do not assume it is announced to users. A title attribute tooltip is also an unreliable place for the exact date, since it is hard or impossible to reach for many keyboard, touch and screen reader users. If the exact time matters, put it in visible text or in visually hidden text that remains in the accessibility tree. If you refresh relative labels on a timer, keep them out of live regions so periodic updates are not announced repeatedly. No assistive technology testing was supplied for this review, so verify behavior with the screen readers your audience uses.
Relative phrases rendered on the server can be frozen in caches and crawler snapshots, where "today" may stay visible long after it stopped being true. A safer pattern is to render the absolute date in the markup and add the relative phrase on the client, so the fallback is always accurate.
<!-- example timestamp -->
<time datetime="2025-01-15T14:05:00Z" data-relative>January 15, 2025</time>
<script>
document.querySelectorAll('time[data-relative]').forEach((el) => {
const absolute = el.dataset.absolute ?? el.textContent;
el.dataset.absolute = absolute;
el.textContent = `${formatRelative(new Date(el.dateTime))} (${absolute})`;
});
</script>
When the page mixes text directions, isolate the relative phrase (for example with a bdi element or dir="auto") so punctuation and numbers around it do not reorder unexpectedly. Some locales may also render digits in a native numbering system. To see which locale the runtime actually used, check the formatter's resolvedOptions().locale rather than assuming the requested one was available.
How it differs from other Intl formatters
| Formatter | Input | Output | Use when |
| Intl.RelativeTimeFormat | Number and unit | Past or future phrase, such as "in 2 weeks" or "yesterday" | Recency relative to now matters more than the exact moment |
| Intl.DateTimeFormat | Date | Localized absolute date and/or time | The exact moment matters or the text will be shared or archived |
| Intl.DurationFormat | Duration object | A length of time, with no past or future direction | Showing how long something took; confirm runtime support first |
Compatibility and evidence gaps
Intl.RelativeTimeFormat is available in current major browsers and recent Node.js versions, but no tested compatibility matrix was supplied for this review. Verify support in your actual targets, especially older embedded webviews and runtimes built with reduced locale data, which can fall back to a different locale. The exact wording comes from locale data that can change between runtime versions, so avoid tests that assert exact output strings across environments; test the value and unit you compute, and treat the final phrase as runtime-dependent.