Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

TypeError: undefined is not a constructor (evaluating 'new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" })')

Tags:

javascript

I have code like:

const rtf = new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" });

which in Safari/605.1.15 triggers the error:

TypeError: undefined is not a constructor (evaluating 'new Intl.RelativeTimeFormat('en', { style: 'short', numeric: "auto" })')

How does one in modern JS work around the fact that Intl API might not be present?

like image 314
hendry Avatar asked Oct 08 '19 09:10

hendry


1 Answers

This method is not well supported. Can I use RelativeTimeFormat?

enter image description here

What you can do is using a package that will emulate the functionnality you need, whatever the browser is.

I've found relative-time-format npm package you can use.


Install

npm install relative-time-format --save

Use

import RelativeTimeFormat from "relative-time-format"
import en from "relative-time-format/locale/en.json"

RelativeTimeFormat.addLocale(en)

// Returns "2 days ago"
new RelativeTimeFormat("en", {
  style: "long" // "long" is the default. Other options: "short", "narrow".
}).format(-2, "day")

To check if the browser is compatible or not :

if (Intl === void 0 || typeof Intl.RelativeTimeFormat !== 'function') {
   // Browser not compatible
}

Alternative :

const rtf = (Intl &&
            Intl.RelativeTimeFormat &&
            new Intl.RelativeTimeFormat('en', {
               style: 'short',
               numeric: "auto",
            })) || false;

if (!rtf) {
   // Not compatible
}
like image 106
Orelsanpls Avatar answered Sep 27 '22 23:09

Orelsanpls