Empresas
Empregos
  • Sobre nós
  • Soluções
    • Publicação de vagas
      Publique sua vaga e receba candidatos qualificados em 48h.
    • Avaliações de candidatos
      Mais de 500 testes técnicos e psicológicos, mais anti-fraude.
    • Headhunting
      Busca executiva personalizada do início ao fim.
    • Folha de Pagamento + EOR
      Dispersão de folha e EOR em mais de 15 países da LATAM.
  • Preços
  • Empregos

0

172
Visualizações
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 Respostas
Responde à pergunta

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 Relatório
Responde à pergunta
Encontrar trabalhos remotos

Descubra a nova forma de encontrar um emprego!

melhores empregos
Principais categorias de trabalho
Empresas
Postar vaga Preços Comercial
Jurídico
Termos e Condições Política de privacidade
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomende algumas ofertas para mim
Preciso de ajuda