cvo
cvo

Reputation: 101

Day Calculation is wrong

I'm making a clock, that calculates the number of days based on the date that the user input. Let's say the user input November 20, 2020. However, the calculate was really off, especially, if I put today date (Jan 06, 2021), then calculate started with -6.

Please take a look and let me know where I went wrong with the calculation. This is my javascript for it:

document.addEventListener('DOMContentLoaded', function() {
    // console.log("js running");
    var days = document.querySelector('.days span');
    var hour = document.querySelector('.hour');
    var min = document.querySelector('.min');
    var second = document.querySelector('.second');
    
    var startDate = new Date(2020, 11, 20);
    days.innerText = Math.floor((new Date - startDate)/86400000);
    countTime();
    
    function countTime() {
        let today = new Date();
        let ms = (today - startDate) % 86400000;
        hour.innerText = Math.floor(ms / 3600000);
        min.innerText = Math.floor(ms % 3600000 / 60000);
        second.innerText = Math.floor(ms % 3600000 % 60000 / 1000);
    }
    
    setInterval(countTime, 1000);
    
}, false);

Upvotes: 1

Views: 54

Answers (1)

blex
blex

Reputation: 25659

In your example, the ms variable was the number of days, and you used it in every other calculation, instead of the actual time difference. You can convert the difference to seconds, and work from there:

document.addEventListener('DOMContentLoaded', function() {
    const $      = document.querySelector.bind(document),
          days   = $('.days span'),
          hour   = $('.hour'),
          min    = $('.min'),
          second = $('.second');
    
    const startDate = new Date(2020, 11, 20);
    countTime();
    
    function countTime() {
        const today     = new Date(),
          diffInSeconds = Math.floor((today - startDate) / 1000);
          
        days.innerText   = Math.floor(diffInSeconds / 86400);
        hour.innerText   = Math.floor(diffInSeconds % 86400 / 3600);
        min.innerText    = Math.floor(diffInSeconds %  3600 / 60);
        second.innerText = Math.floor(diffInSeconds %    60);
    }
    
    setInterval(countTime, 1000);
});
<span class="days"><span></span></span> days
<span class="hour"></span> hours
<span class="min"></span> minutes
<span class="second"></span> seconds

Upvotes: 1

Related Questions