Introduction
Formatting relative times in JavaScript can be a useful way to present information to the user in a human-readable format. A relative time is a time that is relative to the current time, such as “5 minutes ago” or “3 days from now”.
One of the best tools for formatting relative times in JavaScript is the Intl.RelativeTimeFormat
object. This object allows you to specify the language and the style of the relative time, and then use its format()
method to format a relative time value.
Examples
To use the Intl.RelativeTimeFormat
object, you first need to create an instance of the object and specify the language and the style that you want to use. For example, to create a RelativeTimeFormat
object that uses the English language and the long style, you can use the following code:
const timeFormatter = new Intl.RelativeTimeFormat('en', { style: 'long' });
Once you have created the RelativeTimeFormat
object, you can use its format()
method to format a relative time value. The format()
method takes two arguments: the value of the relative time and the unit of time that the value represents (such as “day” or “minute”). For example, to format a relative time of -2 days, you can use the following code:
const relativeTime = timeFormatter.format(-2, 'day');
console.log(relativeTime); // 👉👉 '2 days ago'
The format()
method will return a string that represents the relative time in the language and the style that you specified when creating the RelativeTimeFormat
object. In the example above, the returned string would be “2 days ago” in English.
Here are some more examples of using the Intl.RelativeTimeFormat
object to format relative times in JavaScript:
// Format a relative time of 2 hours in the future
const timeFormatter1 = new Intl.RelativeTimeFormat('en', { style: 'long' });
const relativeTime1 = timeFormatter1.format(2, 'hour');
// Output: "in 2 hours"
// Format a relative time of -1 week in Arabic using the short style
const timeFormatter2 = new Intl.RelativeTimeFormat('ar-SA', { style: 'short' });
const relativeTime2 = timeFormatter2.format(-1, 'week');
// Output: "قبل أسبوع واحد"
// Format a relative time of 5 minutes in the past in Japanese
const timeFormatter3 = new Intl.RelativeTimeFormat('ja', { style: 'long' });
const relativeTime3 = timeFormatter3.format(-5, 'minute');
// Output: "5分前"