Date time in Arabic JavaScrript

Viewed 450

I have a problem in JavaScript function

var tDate = new Intl.DateTimeFormat("ar-US", { 
  day: 'numeric',
  month: 'long',
  year: 'numeric'
}).format(Date.now()) +
  '\xa0\xa0/ \xa0' +
  new Intl.DateTimeFormat("ar-FR-u-ca-islamic", {
  day: 'numeric', 
  month: 'long',
  year: 'numeric'
}).format(Date.now());

console.log(tDate);

the output in Arabic is : 4 أبريل 2020 / 11 شعبان 1441 هـ

in English : April 5, 2020 / Shaʻban 12, 1441 AH

what is the problem in Arabic , number 4 moved to left why??

2 Answers

The output of date formatting using the Intl object is not necessarily consistent across implementations. For me, the OP code produces different results in different browsers:

  • Safari: ٦ أبريل، ٢٠٢٠ / ١٣ شعبان، ١٤٤١
  • Firefox: ٦ أبريل ٢٠٢٠ / ١٣ شعبان ١٤٤١ هـ
  • Chrome: 6 أبريل 2020 / 13 شعبان 1441 هـ

None of them are exactly the same in format or characters.

If you want to ensure the components are in the order you want, use formatToParts, collect the parts then output them in the order you want. Just ensure the result is unambiguous (e.g. use the month name as you've done).

let partsHeg = new Intl.DateTimeFormat('ar-FR-u-ca-islamic', {
  day: 'numeric', 
  month: 'long',
  year: 'numeric'
}).formatToParts(Date.now());

partsHeg.forEach(part => {
  if (part.type != 'literal') {
    console.log(part.type + ': ' + part.value);
  }
});

let partsGre = new Intl.DateTimeFormat('ar-US', {
  day: 'numeric', 
  month: 'long',
  year: 'numeric'
}).formatToParts(Date.now());

partsGre.forEach(part => {
  if (part.type != 'literal') {
    console.log(part.type + ': ' + part.value);
  }
});

You can fix this by adding a one (1) statement/code of the RTL Unicode to fix the direction. This happens when the last or first letter in an Arabic text is a Latin char.

let RTL = "\u200F";       // Added ****
var tDate = RTL + new Intl.DateTimeFormat("ar-US", {  // Added RTL before
  day: 'numeric',
  month: 'long',
  year: 'numeric'
}).format(Date.now()) +
  '\xa0\xa0/ \xa0' +
  new Intl.DateTimeFormat("ar-FR-u-ca-islamic", {
  day: 'numeric', 
  month: 'long',
  year: 'numeric'
}).format(Date.now());

console.log(tDate);                  // You can add RTL here instead console.log(RTL+tDate); 

Related