Encodera

Thanks for reading!

Donate to the site — we work hard for you.

JavaScript reference

Intl.RelativeTimeFormat

Formats relative time: 3 days ago, in 1 hour.

Available since: ES2020

Syntax

new Intl.RelativeTimeFormat(locales, options)

Parameters

ParameterTypeDescription
localesstringOptional. The language and region.
optionsobjectOptional. 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 hours

Another language:

const rtf = new Intl.RelativeTimeFormat('de');
 
console.log(rtf.format(-5, 'minute'));

Output:

vor 5 Minuten

Notes

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

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.

Thanks for reading!

Donate to the site — we work hard for you.