Empresas
Empleos
  • Sobre nosotros
  • Soluciones
    • Publicación de vacantes
      Publica tu vacante y recibe candidatos calificados en 48h.
    • Evaluación de candidatos
      500+ pruebas técnicas y psicológicas, más anti-fraude.
    • Headhunting
      Búsqueda ejecutiva a la medida de principio a fin.
    • Nómina + EOR
      Dispersión de nómina y EOR en más de 15 países de LATAM.
  • Precios
  • Empleos

0

170
Vistas
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 Respuestas
Responde la pregunta

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 Denunciar
Responde la pregunta
Encuentra empleos remotos

¡Descubre la nueva forma de encontrar empleo!

Top de empleos
Top categorías de empleo
Empresas
Publicar vacante Precios Comercial
Legal
Términos y condiciones Política de privacidad
© 2026 PeakU Inc. All Rights Reserved.
Andres GPT
Recomiéndame algunas ofertas
Necesito ayuda