date.toLocaleDateString conversion with locale Arabic yields different results in Chrome and firefox

Viewed 412

I have a function that formats date using date.toLocaleDateString I see that when I have locale set to 'Arabic' the results in Chrome are different from what is on FF and Safari.

let date = new Date();
const dateOptions = {
  day: "2-digit",
  month: "2-digit",
  year: "numeric"
};

console.log(date.toLocaleDateString("ar", dateOptions));

Here is the code-sandbox link https://codesandbox.io/s/loving-haslett-mj6b0?file=/src/index.js

In chrome, date shows up as 27‏/01‏/2021 whereas in FF and Safari, it is converted to Arabic.

How can we ensure consistency across browsers?

2 Answers

Try to use ar-eg instead of just ar:

console.log(date.toLocaleDateString("ar-eg", dateOptions));

But remember that the toLocaleDateString implentation is always application dependent, furthermore there are browsers that do not implement the locale/option parameters.

You can check the language and options support by using the following functions:

function dateSupportsLocales(language) {
  try {
    new Date().toLocaleDateString(language);
  } catch (e) {
    return e.name !== 'RangeError';
  }
  return true;
}

function dateSupportsOptions() {
  try {
    new Date().toLocaleDateString('en', {});
    return true;
  }
  catch (e) { }
  return false;
}

Check also the Date.prototype.toLocaleDateString MDN Reference for more informations.

You are not explicitly stating the numberingSystem and you leave it to the browser implementation to decide.

if you state the numberingSystem as arab then you get consistent results:

Here is an example:

Just add u-nu-arab after the locale ar. No need to give a country code.

let date = new Date();
const dateOptions = {
  day: "2-digit",
  month: "2-digit",
  year: "numeric"
};

console.log(date.toLocaleDateString("ar-u-nu-arab", dateOptions));

Related