I have a simple page that shows current time and date:
<p class="clock" id="clock-time"></p>
<h3 class="clock-date" id="clock-date"></h3>
And clock.js:
window.onload = updateClock;
function updateClock() {
let dt = new Date();
let time =
dt.getHours() +
':' +
(dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) +
':' +
(dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds());
let date =
(dt.getDay() < 10 ? '0' + dt.getDay() : dt.getDay()) +
'-' +
(dt.getMonth() < 10 ? '0' + dt.getMonth() : dt.getMonth()) +
'-' +
dt.getFullYear();
document.getElementById('clock-time').innerText = time;
document.getElementById('clock-date').innerText = date;
setTimeout(updateClock, 6000);
}
However it shows correct time, but not correct date:
screenshot
2
Answers
getDay should be getDate
and getMonth is jan = 0 so +1 it
The issue with the date lies in how the getDay() and getMonth() methods are used:
getDay(): Returns the day of the week (0 for Sunday, 1 for Monday, etc.), not the day of the month. You should use getDate() instead to get the correct day of the month.
getMonth(): Returns the month index (0 for January, 1 for February, etc.), so you need to add 1 to get the correct month number.