Format date in JS, and keep the date format for different locales

Advertisements

I have a setting for a date format that looks like:

const shortMonth12 = {
year: 'numeric', month: 'short', day: 'numeric', hour: '2-digit', minute: '2-digit', hour12: 'true'  };

Which will give me the following date format:

console.log(date.toLocaleString('en-US', shortMonth12)) // "Mar 28, 2022, 01:55 PM"

Great, it works and we have the date format we want. We dont want to change it.

But we also want to also translate the month name. But problem is the format itself also changes when providing another locale. For example:

console.log(date.toLocaleString('sv-SE', shortMonth12)); // "28 mars 2022 01:55 em"

So, we want to use the locales to translate the months, but also keep the formatting the same. Is it possible the way the implementation looks like?

>Solution :

So, we want to use the locales to translate the months, but also keep the formatting the same.

No, since toLocaleString uses the provided locale to format the date, the outcome is depending on the locale.

If you use 2 different locale’s that have different date formats, like en-US and sv-SE you’ll get different formats, as intended.

en-US: Mar 28, 2022, 02:19 PM
sv-SE: 28 mars 2022 02:19 em


You can get the desired outcome by creating the string manual, this requires some more logic and goes against the idea behind toLocaleString.

Use the functions like toLocaleTimeString and getFullYear to create variables based on the locale, then create a string with the desired format, for example:

const customFormat = (date, locale) => {
  let d = date.getDate(),
      m = date.toLocaleString(locale, { month: 'long' }),
      y = date.getFullYear(),
      t = date.toLocaleTimeString(locale, { hour: '2-digit', minute: '2-digit', hour12: 'true' });
      
  return `${d} ${m}, ${y}, ${t}`;
}

const d  = new Date();
const d1 = customFormat(d, 'en-US');
const d2 = customFormat(d, 'sv-SE');

console.log(d1); // 28 March, 2022, 02:25 PM
console.log(d2); // 28 mars, 2022, 02:25 em

Leave a ReplyCancel reply