Relative Time Formatting with JavaScript (No Libraries) - Intl RelativeTimeFormat

The Intl.RelativeTimeFormat object gives us language-sensitive relative time formatting.

This is particularly useful when displaying timestamps, time remaining, or time elapsed in a user-friendly way.

It makes getting those fancy-looking messages you see easier than a plain old time since, eg. "In 1 month", "1 day ago".

Intl.RelativeTimeFormat

Follow this simple tutorial on using Intl.RelativeTimeFormat. 👇

Step 1

Create an instance of Intl.RelativeTimeFormat.

Syntax:

// Parameters are optional
new Intl.RelativeTimeFormat(locales, options)

To create an instance, you can provide a locale and optional formatting options:

// new Intl.RelativeTimeFormat(locales, options)
const relativeTimeFormat = new Intl.RelativeTimeFormat('en-US', {
  numeric: 'auto', // Other options: "always" - defaults to "always"
  style: 'long', // Other options: "short", "narrow" - defaults to "long"
});

In this example, the locale is 'en-US', which specifies English as used in the United States.

The numeric option is set to 'auto', which allows the formatter to use a more compact representation when possible (e.g., "in 1 day" might become "tomorrow"). The style option is set to 'long', which specifies that the output should use the long form (e.g., "in 3 minutes" instead of "in 3 min").

Step 2

Call the format method on the Intl.RelativeTimeFormat instance, providing the time value and the unit of time:

console.log(relativeTimeFormat.format(-1, 'day')); // 👉 "yesterday"
console.log(relativeTimeFormat.format(1, 'day')); // 👉 "tomorrow"
console.log(relativeTimeFormat.format(5, 'minute')); // 👉 "in 5 minutes"
console.log(relativeTimeFormat.format(-5, 'minute')); // 👉 "5 minutes ago"
console.log(relativeTimeFormat.format(-1, 'second')); // 👉 "1 second ago"

Using this knowledge, you can display timestamps, time remaining, or time elapsed in a user-friendly way. 🎉


Follow me on Twitter or connect on LinkedIn.

🚨 Want to make friends and learn from peers? You can join our free web developer community here. 🎉

JSWeb DeveloperJavaScript
Avatar for Niall Maher

Written by Niall Maher

Founder of Codú - The web developer community! I've worked in nearly every corner of technology businesses: Lead Developer, Software Architect, Product Manager, CTO, and now happily a Founder.

Loading

Fetching comments

Hey! 👋

Got something to say?

or to leave a comment.