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?
This method is not well supported. Can I use RelativeTimeFormat?
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
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With