Open In App

JavaScript Intl RelativeTimeFormat() Constructor

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.

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.




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




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:

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

Article Tags :