JavaScript-Programm zum Formatieren des Datums

In diesem Beispiel lernen Sie, ein JavaScript-Programm zu schreiben, das ein Datum formatiert.

Um dieses Beispiel zu verstehen, sollten Sie die folgenden JavaScript-Programmierthemen kennen:

  • JavaScript if… else Anweisung
  • JavaScript Datum und Uhrzeit

Beispiel 1: Formatieren Sie das Datum

 // 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);

Ausgabe

 26.08.2020 26.08.2020 26.08.2020 26.08.2020

Im obigen Beispiel ist

1. Das new Date()Objekt gibt das aktuelle Datum und die aktuelle Uhrzeit an.

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

2. Die getDate()Methode gibt den Tag ab dem angegebenen Datum zurück.

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

3. Die getMonth()Methode gibt den Monat ab dem angegebenen Datum zurück.

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

4. 1 wird der getMonth()Methode hinzugefügt, da der Monat bei 0 beginnt . Daher ist Januar 0 , Februar 1 und so weiter.

5. Das getFullYear()gibt das Jahr ab dem angegebenen Datum zurück.

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

Anschließend können Sie das Datum in verschiedenen Formaten anzeigen.

Interessante Beiträge...