Intl.RelativeTimeFormat
Formats relative time: 3 days ago, in 1 hour.
Available since: ES2020
Syntax
new Intl.RelativeTimeFormat(locales, options)Parameters
| Parameter | Type | Description |
|---|---|---|
| locales | string | Optional. The language and region. |
| options | object | Optional. numeric: always or auto; style: long, short, narrow. |
Return value
Intl.RelativeTimeFormatAn object with a format(value, unit) method.
Examples
Past and future:
const rtf = new Intl.RelativeTimeFormat('en', { numeric: 'auto' });
console.log(rtf.format(-3, 'day'));
console.log(rtf.format(1, 'day'));
console.log(rtf.format(2, 'hour'));Output:
3 days ago
tomorrow
in 2 hoursAnother language:
const rtf = new Intl.RelativeTimeFormat('de');
console.log(rtf.format(-5, 'minute'));Output:
vor 5 MinutenNotes
The formatter does not compute the difference itself: you pass the number and the unit (second, minute, hour, day, week, month, year). The numeric: 'auto' option gives words like yesterday instead of 1 day ago.
See also
- Intl.DateTimeFormat — Formats dates and times by language rules.
- Date.prototype.getTime — Returns the date as a number of milliseconds.
Related recipes
In the tutorial
- Formatting with Intl — Locale-aware formatting of numbers, money, dates and plural words in JavaScript: toLocaleString, Intl.NumberFormat, Intl.DateTimeFormat and Intl.PluralRules.