Programa JavaScript para formatear la fecha

En este ejemplo, aprenderá a escribir un programa JavaScript que formateará una fecha.

Para comprender este ejemplo, debe tener el conocimiento de los siguientes temas de programación de JavaScript:

  • Declaración de JavaScript if … else
  • Fecha y hora de JavaScript

Ejemplo 1: Aplicar formato a la fecha

 // program to format the date // get current date let currentDate = new Date(); // get the day from the date let day = currentDate.getDate(); // get the month from the date // + 1 because month starts from 0 let month = currentDate.getMonth() + 1; // get the year from the date let year = currentDate.getFullYear(); // if day is less than 10, add 0 to make consistent format if (day < 10) ( day = '0' + day; ) // if month is less than 10, add 0 if (month < 10) ( month = '0' + month; ) // display in various formats const formattedDate1 = month + '/' + day + '/' + year; console.log(formattedDate1); const formattedDate2 = month + '-' + day + '-' + year; console.log(formattedDate2); const formattedDate3 = day + '-' + month + '-' + year; console.log(formattedDate3); const formattedDate4 = day + '/' + month + '/' + year; console.log(formattedDate4);

Salida

 26/08/2020 26/08/2020 26-08-2020 26/08/2020

En el ejemplo anterior,

1. El new Date()objeto da la fecha y hora actuales.

 let currentDate = new Date(); console.log(currentDate); // Output // Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)

2. El getDate()método devuelve el día a partir de la fecha especificada.

 let day = currentDate.getDate(); console.log(day); // 26

3. El getMonth()método devuelve el mes a partir de la fecha especificada.

 let month = currentDate.getMonth() + 1; console.log(month); // 8

4. Se agrega 1 al getMonth()método porque el mes comienza desde 0 . Por tanto, enero es 0 , febrero es 1 y así sucesivamente.

5. getFullYear()Devuelve el año a partir de la fecha especificada.

 let year = currentDate.getFullYear(); console.log(year); // 2020

Luego, puede mostrar la fecha en diferentes formatos.

Articulos interesantes...