Ebben a példában megtanul olyan JavaScript programot írni, amely formázza a dátumot.
A példa megértéséhez ismernie kell a következő JavaScript programozási témákat:
- JavaScript, ha… más nyilatkozat
- JavaScript dátum és idő
1. példa: A dátum formázása
// 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);
Kimenet
2020.08.26. 2020.08.26., 20.08.2020, 20.8.26
A fenti példában
1. Az new Date()
objektum megadja az aktuális dátumot és időt.
let currentDate = new Date(); console.log(currentDate); // Output // Wed Aug 26 2020 10:45:25 GMT+0545 (+0545)
2. A getDate()
módszer a megadott dátumtól kezdve adja vissza a napot.
let day = currentDate.getDate(); console.log(day); // 26
3. A getMonth()
módszer a megadott dátumtól kezdve adja vissza a hónapot.
let month = currentDate.getMonth() + 1; console.log(month); // 8
4. 1 hozzáadódik a getMonth()
módszerhez, mert a hónap 0- tól indul . Ennélfogva január 0 , február 1 és így tovább.
5. A getFullYear()
megadott dátumtól kezdve adja vissza az évet.
let year = currentDate.getFullYear(); console.log(year); // 2020
Ezután megjelenítheti a dátumot különböző formátumokban.