The idea of Intl.RelativeTimeFormat is that it gives the ability to format to create an instance of relative time format function, with some pre defined settings or options that the output can follow.
The syntax of Intl.RelativeTimeFormat can take one of the following shapes:
new Intl.RelativeTimeFormat()
new Intl.RelativeTimeFormat(locales)
new Intl.RelativeTimeFormat(locales, options)
To create a relative time formatter:
- Create an object using the
Intl.RelativeTimeFormat()
constructor.
Note:
Intl.RelativeTimeFormat()
can only be constructed withnew
. Attempting to call it withoutnew
throws aTypeError
.
- Use the
format()
method on the constructor.
Examples
To format a time in English strings, we can do the following:
const rtf = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtf.format(2, 'quarters'));
// expected output: "in 2 qtrs."
In case you want to format time in the past, you can pass a negative value to the format function, as the following:
const rtf = new Intl.RelativeTimeFormat('en', { style: 'narrow' });
console.log(rtf.format(-2, 'quarters'));
// expected output: "2 qtrs. ago"
The first argument the Intl.RelativeTimeFormat accept is the locale
which can be either a string or an array of strings with BCP 47 language tag.
The second argument is the options
and can take any of the following options:
numeric
property, which can take one of two possible values:always
: We use this property in case we need the output to be of the shape:1 day ago
.
auto
: We use this property in case we need the output to be of the shapeyesterday
and not always numeric.
style
property, can be used to define the length of the formatted message:"long"
: It would results in string likein 1 month
"short"
: It would results in string likein 1 mo.
"narrow"
: It would results in string similar to the short styles for some locales likein 1 mo.
An example of using numeric = auto
// Create a relative time formatter in your locale
// with numeric: "auto" option value passed in.
const rtf = new Intl.RelativeTimeFormat("en", { numeric: "auto" });
// Format relative time using negative value (-1).
rtf.format(-1, "day");
// expected output: "yesterday"
// Format relative time using positive day unit (1).
rtf.format(1, "day");
// expected output: "tomorrow"
The format
method takes 2 parameters:
- A
value
to use in the internationalized message. - The
unit
to use in the message. Possible values are:year
,quarter
,month
,week
,day
,hour
,minute
andsecond
.
In the example above, we passed day
as the unit
to the format
method.
Formatting dates to Relative Time (time ago)
In this example we gonna show how to format dates/timestamps as relative time.
const DAY_MILLISECONDS = 1000 * 60 * 60 * 24;
function getRelativeTime(timestamp) {
const rtf = new Intl.RelativeTimeFormat('en', {
numeric: 'auto',
});
const daysDifference = Math.round(
(timestamp - new Date().getTime()) / DAY_MILLISECONDS,
);
return rtf.format(daysDifference, 'day');
}
// (Today is 2nd Sep, 2022
// 👇️ 18 days ago
console.log(getRelativeTime(new Date('2022-08-15').getTime()));
// 👇️ 3 days ago
console.log(getRelativeTime(new Date('2022-08-30').getTime()));
// 👇️ yesterday
console.log(getRelativeTime(new Date('2022-09-01').getTime()));
// 👇️ today
console.log(getRelativeTime(new Date().getTime()));
The getTime method returns the number of milliseconds elapsed between 1st of January, 1970 00:00:00 and the given date.
We subtracted the current timestamp from the passed in timestamp and converted the result from milliseconds to days.The result can be either a negative (timestamps in the past) or a positive (timestamps in the future) integer.
The function returns a string, formatted as: 2 days ago
, in 5 days
, yesterday
, etc.
That’s it for Javascript Intl.RelativeTimeFormat formatting, And as always happy coding!
Photo from unsplash