Check if Intl.DateTimeFormat options.dateStyle is supported?

552 Views Asked by At

Is there any way to check if the dateStyle option is supported in the Intl.DateTimeFormat API?

I just became aware that older versions of Safari support Intl.DateTimeFormat but not options.dateStyle. I will have to do something else to handle date formatting on old Safari but I don't want to version-sniff.

1

There are 1 best solutions below

0
On BEST ANSWER

The usual dictionary trap should do (though I didn't test it in old Safari, and I know of at least one API where they were getting a property even if they didn't support it, so if you can, test it on your side).

The "dictionary trap" is a simple JS object on which you add a getter for the property you want to see if the API supports it or not. If the getter has been called, we can assume that the property is supported by the UA.

Beware though this is not free, this will create an actual instance of the interface being tested. To avoid that a general trick is to use a well-supported property with a high alpha value, and to throw in the getter of that property. This way we avoid creating an instance. This isn't possible for all properties, but here for dateStyle we're lucky, timeZone comes after and it should have a pretty good support.

const supportDateStyle = (() => {
  let supported = false;
  try {
    new Intl.DateTimeFormat('en-US', {
      get dateStyle() { supported = true; },
      get timeZone() { throw ""; }
    });
  }
  catch(err) { }
  return supported;
})();

console.log({supportDateStyle});

Now, if you're afraid of some quirks in some UAs, a maybe more bullet-proof solution is to use the resolvedOptions() method, and check whether the dateStyle property is there or not. Though this will create an instance of the formatter.

const supportDateStyle = new Intl.DateTimeFormat("en-US", {dateStyle: "full"})
  .resolvedOptions().dateStyle === "full";

console.log({supportDateStyle});