skip to Main Content

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


  1. getDay should be getDate
    and getMonth is jan = 0 so +1 it

    Login or Signup to reply.
  2. 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.

    window.onload = updateClock;
    
    function updateClock() {
        let dt = new Date();
        
        // Format the time
        let time =
            dt.getHours() +
            ':' +
            (dt.getMinutes() < 10 ? '0' + dt.getMinutes() : dt.getMinutes()) +
            ':' +
            (dt.getSeconds() < 10 ? '0' + dt.getSeconds() : dt.getSeconds());
        
        // Format the date
        let date =
            (dt.getDate() < 10 ? '0' + dt.getDate() : dt.getDate()) +
            '-' +
            (dt.getMonth() + 1 < 10 ? '0' + (dt.getMonth() + 1) : dt.getMonth() + 1) +
            '-' +
            dt.getFullYear();
        
        // Update the DOM elements
        document.getElementById('clock-time').innerText = time;
        document.getElementById('clock-date').innerText = date;
        
        // Update every second
        setTimeout(updateClock, 1000);
    }
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search