Transform a given date in yyyy-mm-dd format to string in javaScript?

Question:

I capture a date in the yyy-mm-dd (2016-06-30) and I want to give it a more user-friendly format, I am looking for the following:

2016-06-30 = 6 de Junio del 2016 
2016-06-30 = Junio (Mostrar el mes dada la fecha)
2016-06-30 = Jueves (Mostrar el día, suponiendo que el 06 sea Jueves).

Answer:

This is the standard option, available in most browsers (all modern ones), toLocaleDateString

An example.

var fecha = new Date();
var options = { year: 'numeric', month: 'long', day: 'numeric' };

console.log(
  fecha.toLocaleDateString("es-ES", options)
);

Another that includes the day of the week:

var fecha = new Date(1995, 11, 17);
var options = { weekday: 'long', year: 'numeric', month: 'long', day: 'numeric' };

console.log(
  fecha.toLocaleDateString("es-ES", options)
);

fecha = new Date("2017-08-21");
console.log(
  fecha.toLocaleDateString("es-ES", options)
);

If you look at the documentation noted above, there are different options to show all or only some of the parts in the formatted date.

Depending on the options you use, you can show only the day, or the month. Also you can, if you do not include the locale ("es-ES" – Spanish of Spain) leave it so that it uses the local configuration of the user. This is usually a good practice since the user has a preferred format configured and it is good to respect it.

Salu2

Scroll to Top