Open In App

JavaScript Intl RelativeTimeFormat() Constructor

Last Updated : 12 Apr, 2023
Improve
Improve
Like Article
Like
Save
Share
Report

JavaScript Intl RelativeTimeFormat() Constructor is used for creating Intl.RelativeTimeFormat object. This constructor is created using the new keyword. If we create the constructor without the new keyword it will give a TypeError.

Syntax:

new Intl.RelativeTimeFormat(loc, opt)

Parameters: It has two parameters both are optional.

  • loc: It is a String or an array of Strings that contains the general form and interpretation of arguments
  • opt: It is an object which contains properties like localeMatcher and style and numeric.

Return Value: An Intl.RelativeFormat object.

Below examples illustrate the JavaScript Intl RelativeTimeFormat() Constructor:

Example 1: This example creates a basic RelativeTimeFormat Object and uses it to format the time.

Javascript




const timeFormat = new Intl.RelativeTimeFormat("en",{
    localeMatcher: "lookup",
    numeric: "always",
    style: "short",
});
console.log(timeFormat.format(-2,"year"));
console.log(timeFormat.format(-3,"week"));


Output: 

2 yr. ago
VM162:8 3 wk. ago

Example 2: This example uses RelativeTimeFormat Object with auto property

Javascript




const timeFormat = new Intl.RelativeTimeFormat("en",{
    localeMatcher: "lookup",
    numeric: "auto",
    style: "long",
});
  
console.log(timeFormat.format(2,"day"));
console.log(timeFormat.format(-3,"day"));


Output:

in 2 days
3 days ago

Supported Browsers:

  • Chrome
  • Edge
  • Firefox
  • Opera
  • Safari

We have a complete list of JavaScript Intl methods to check please go through, the JavaScript Intl Reference article


Like Article
Suggest improvement
Share your thoughts in the comments

Similar Reads