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 Capture Screenshots with Puppeteer In NodeJS

How to Capture Screenshots with Puppeteer In NodeJS

To Capture Screenshots with Puppeteer: Launch a Browser Instance Navigate to the Web Page Capture the Screenshot Introduction: Puppeteer is a powerful Node.js library that allows developers…

How to Minimize Puppeteer Browser Window To Tray

How to Minimize Puppeteer Browser Window To Tray

Puppeteer is a powerful tool for automating tasks in headless or non-headless web browsers using JavaScript. While Puppeteer is often used to perform actions within a browser,…

Intercepting Responses in Node.js with Puppeteer

Intercepting Responses in Node.js with Puppeteer

Introduction: Puppeteer is a powerful Node.js library that provides a high-level API for controlling headless Chrome or Chromium browsers. It’s widely used for web scraping, automated testing,…

Mastering React Component Re-rendering in Jest

Mastering React Component Re-rendering in Jest

In this hands-on guide, we’ll explore the art of optimizing React component re-rendering within Jest tests. By combining theory with practical coding examples, you’ll gain a deep…

Eliminating Nesting Loops in React Rendering

Eliminating Nesting Loops in React Rendering

React has ushered in a new era of web application development with its component-based structure, promoting code reusability and maintainability. But as projects evolve, achieving optimal performance…

Exploring Type and Interface Usage in TypeScript

Exploring Type and Interface Usage in TypeScript

TypeScript has gained immense popularity by bridging the gap between dynamic JavaScript and static typing. Two of its fundamental features, “Type” and “Interface,” play pivotal roles in…

Leave a Reply

%d bloggers like this: