V tomto príklade sa naučíte písať program JavaScript, ktorý naformátuje dátum.
Aby ste pochopili tento príklad, mali by ste mať znalosti nasledujúcich tém programovania v jazyku JavaScript:
- Vyhlásenie JavaScript, ak … else
- Dátum a čas JavaScriptu
Príklad 1: Formátovanie dátumu
// 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);
Výkon
26. 8. 2020 26. 8. 2020 26. 8. 2020 26. 8. 2020
Vo vyššie uvedenom príklade
1. new Date()
Objekt dáva aktuálny dátum a čas.
let currentDate = new Date(); console.log(currentDate); // Output // Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)
2. getDate()
Metóda vráti deň od zadaného dátumu.
let day = currentDate.getDate(); console.log(day); // 26
3. getMonth()
Metóda vráti mesiac od zadaného dátumu.
let month = currentDate.getMonth() + 1; console.log(month); // 8
4. 1 je pridaný k getMonth()
metóde, pretože mesiac začína od 0 . Preto je január 0 , február 1 atď.
5. getFullYear()
Vráti rok od zadaného dátumu.
let year = currentDate.getFullYear(); console.log(year); // 2020
Potom môžete zobraziť dátum v rôznych formátoch.