Intl.DateTimeFormat difference beetween node and devtools

Viewed 434

I was writting unit test today for this function:

/**
 * recives a timestamp and format to 'yyyy/mm/dd hh:mm'
 */
function formatCurrentDate(date) {
  return Intl.DateTimeFormat('ja-JP',
    {
      hour: '2-digit',
      minute: '2-digit',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).format(date);
}

with this test:

test('it should format the current date', () => {
  expect(formatCurrentDate(new Date().getTime())).toMatch(new RegExp(/^\d{4}\/\d{2}\/\d{2}\s{1}\d{2}\:\d{2}$/));
}); 

but always is failing because the node returns to me a different date format

so i just realized runnig formatCurrentDate() on devtools i got the correct format: '2020/08/25 14:50'

but when i run the same funciton on my cmd (typing node and pasting the function) i got: '2020-08-25 14:50'

why is this happening??

1 Answers

Intl.DateTimeFormat attempts to provide a culturally sensitive formatting of date components based on a language code. There is no definitive specification or standard to map language codes to formats, it's implementation dependent. Also, if a particular language isn't supported, an implementation may fall back to a default format. So different implementations may well give different formats for the same language code and options.

So it's not a good idea to rely on Intl.DateTimeFormat to format a date and expect it to have a precise format. You might use the formatToParts method to get the appropriate parts, then manually put them in the format you want.

If you want a particular format, you should create it manually with a bespoke function or formatting library that you might write yourself or use one of the many available on the web. There are already many questions and answers on that topic on stackoverflow.

PS. It's helpful to post code as a runnable snippet, e.g.

/**
 * recives a timestamp and format to 'yyyy/mm/dd hh:mm'
 */
function formatCurrentDate(date = new Date()) {
  return Intl.DateTimeFormat('ja-JP',
    {
      hour: '2-digit',
      minute: '2-digit',
      year: 'numeric',
      month: '2-digit',
      day: '2-digit'
    }).format(date);
}

console.log(formatCurrentDate());

Related