Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

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

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.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading