Business
Jobs
  • About Us
  • Solutions
    • Job Postings
      Post your job and receive qualified candidates in 48h.
    • Candidate Assessments
      500+ technical and psychological tests, plus anti-fraud.
    • Headhunting
      Tailor-made executive search from start to finish.
    • Payroll + EOR
      Payroll dispersal and EOR across 15+ LATAM countries.
  • Pricing
  • Jobs

0

167
Views
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.

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?

about 4 years ago · Juan Pablo Isaza
1 answers
Answer question

0

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

about 4 years ago · Juan Pablo Isaza Report
Answer question
Find remote jobs

Discover the new way to find a job!

Top jobs
Top job categories
Business
Post vacancy Pricing Sales
Legal
Terms and conditions Privacy policy
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Show me some job opportunities
There's an error!