W tym przykładzie nauczysz się pisać program JavaScript, który będzie wyświetlał aktualną datę.
Aby zrozumieć ten przykład, powinieneś znać następujące tematy programowania JavaScript:
- Data i godzina JavaScript
Przykład: wyświetl aktualną datę
// program to display the date // get local machine date time const date = new Date(); // get the date as a string const n = date.toDateString(); // get the time as a string const time = date.toLocaleTimeString(); // display date console.log('Date: ' + n); // display time console.log('Time: ' + time);
Wynik
Data: środa, 26 sierpnia 2020 r., Godzina: 13:13:12
W powyższym przykładzie new Date()
konstruktor służy do tworzenia obiektu daty. Następnie,
1. new Date()
Podaje aktualną datę i godzinę.
const date = new Date(); console.log(date); // Sun Aug 23 2020 10:46:38 GMT+0545 (+0545)
2. toDateString()
Metoda zwraca część obiektu Date zawierającą datę.
const n = date.toDateString(); console.log(n); // Wed Aug 26 2020
3. toLocaleTimeString()
Metoda zwraca część czasu z obiektu daty.
const time = date.toLocaleTimeString(); console.log(time); // 1:13:12 PM