How to format dates with Intl.RelativeTimeFormat

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 with new. Attempting to call it without new throws a TypeError.

  • 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 shape yesterday and not always numeric.
  • style property, can be used to define the length of the formatted message:
    • "long": It would results in string like in 1 month
    • "short": It would results in string like in 1 mo.
    • "narrow": It would results in string similar to the short styles for some locales like in 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:

  1. value to use in the internationalized message.
  2. The unit to use in the message. Possible values are: yearquartermonthweekdayhourminute and second.

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 agoin 5 daysyesterday, etc.

That’s it for Javascript Intl.RelativeTimeFormat formatting, And as always happy coding!

Photo from unsplash

Related Posts

How to remove highcharts.com credits link

How to remove highcharts.com credits link

Highcharts is a popular JavaScript charting library that offers a wide range of interactive and customizable charts for developers. However, if you’re using the free version of…

Highcharts Place text in the center of a pie chart

Highcharts Place text in the center of a pie chart

To place text in the center of a pie chart in Highcharts, you can use the chart.renderer object to create a custom label and position it in…

Test design breakpoints using jest and react-testing-library

Test responsive design using jest and react-testing-library

Testing design breakpoints in React applications is an important aspect of front-end development. It ensures that the components look and behave as expected on different screen sizes….

Testing React-Query with Jest and React-testing-library

Testing React-Query with Jest and React-testing-library

Introduction In this article we will cover the basic usage of testing useQuery hook from tanstack/react-query library, along with how to test it using jest and react-testing-library….

Highcharts How To Change Series Color with examples

Highcharts How To Change Series Color with examples

To change the color of a series in Highcharts, there are a set of options we are going to discover in this article. Option 1: Using the…

A quick introduction to Javascript shadow DOM

A quick introduction to Javascript shadow DOM

Introduction JavaScript Shadow DOM is a powerful tool for creating isolated and reusable components in web development. It allows developers to create custom elements with their own…

Leave a Reply

%d bloggers like this: