依照官網的方法介紹,我先宣告一個 Date 的物件,並取用裡面的年、月、日、時、分、秒,並用 ES6 的寫法組成我要的格式,並渲染在網頁上。
month 這個地方比較奇怪,是從 0 開始,其他都從 1 開始。
1 2 3 4 5 6 7 8 9
let newDate = newDate(); let year = newDate.getFullYear(); let month = newDate.getMonth() + 1; let days = newDate.getDate(); let hour = newDate.getHours(); let mins = newDate.getMinutes(); let sec = newDate.getSeconds(); let clockJSRead = `${year}/${month}/${days}${hour}:${mins}:${sec}`; date.textContent = clockJSRead;
setInterval(function () { let newDate = newDate(); let year = newDate.getFullYear(); let month = newDate.getMonth() + 1; let days = newDate.getDate(); let hour = newDate.getHours(); let mins = newDate.getMinutes(); let sec = newDate.getSeconds(); let clockJSRead = `${year}/${month}/${days}${hour}:${mins}:${sec}`; date.textContent = clockJSRead; }, 1000);
這樣就完成了,不過上方程式碼看起來很髒,所以這邊改寫成下方這樣:
1 2 3 4 5 6 7 8 9 10 11 12 13 14
let date = document.querySelector("#date");
functionupdateDate() { let newDate = newDate(); let year = newDate.getFullYear(); let month = newDate.getMonth() + 1; let days = newDate.getDate(); let hour = newDate.getHours(); let mins = newDate.getMinutes(); let sec = newDate.getSeconds(); let clockJSRead = `${year}/${month}/${days}${hour}:${mins}:${sec}`; date.textContent = clockJSRead; } setInterval(updateDate, 1000);