0

Lets consider the following code:

console.log(new Intl.DateTimeFormat('pl-PL', {
  year: 'numeric',
  month: '2-digit',
  day: '2-digit'
}).format(new Date(2019, 2, 4)));

In Node JS it gives 2019-03-04 but in chrome browser it returns 04.03.2019.

Why?

My question is similar to:

Why Intl.DateTimeFormat produces different result in different browsers?

Where is official documentation for node and chrome and when can I read about these differencies.

Update:

It can be helpful for someone so I will add that to enforce common format I am using this code:

export const useDashInDate = (dateString: string): string => {
    return /\d{4}-\d{2}-\d{2}/.test(dateString) ? dateString : dateString.split('.').reverse().join('-');
};
Daniel
  • 5,039
  • 2
  • 28
  • 53

1 Answers1

1

The format of the string returned by DateTimeFormat.format is based on the language code, but there is no specification mapping languages to formats. So each implementation is free to map language to format however it wants. Mostly they're consistent, but not always. If a particular language is not supported, it may fall back to a default (e.g. ISO 8601 or a generic language code like en).

If you want a specific format, do it manually with your own function or use a library, see How to format a JavaScript date.

E.g. you might use formatToParts with a more general language code:

function format(date) {
  let {year, month, day} = new Intl.DateTimeFormat('pl', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit'
  }).formatToParts(date).reduce((acc, part) => {
    if (part.type != 'literal') {
      acc[part.type] = part.value;
    }
    return acc;
  }, Object.create(null));
  return `${day}.${month}.${year}`;
}
  
console.log(format(new Date(2019, 2, 4)));
RobG
  • 124,520
  • 28
  • 153
  • 188