skip to Main Content

this code returns the time in negative im a newbie in web development, kindly help

let countDate = new Date('April 1, 2023 00:00:00').getTime();

function countDown() {

    let now = new Date().getTime();
    gap = countDate - now;

    let second = 1000;
    let minute = second * 60;
    let hour = minute * 60;
    let day = hour * 24;

    let d = Math.floor(gap / (day));
    let h = Math.floor((gap % (day)) / (hour));
    let m = Math.floor((gap % (hour)) / (minute));
    let s = Math.floor((gap % (minute)) / (second));

    document.getElementById('day').innerText = d;
    document.getElementById('hour').innerText = h;
    document.getElementById('minute').innerText = m;
    document.getElementById('second').innerText = s;

}

setInterval(function() {
    countDown();
}, 1000)

enter image description here

tried to rectify the code but unable to understand it fully, kindly help what needs to be done in this

5

Answers


  1. The countDate variable is set to a date and time in the past

    Login or Signup to reply.
  2. The getTime() method returns the number of milliseconds since the epoch, which is defined as the midnight at the beginning of January 1, 1970, UTC. (Definition on MDN)

    Since April 1, 2023 00:00:00 is in the past, new Date().getTime() returns a greater number than new Date('April 1, 2023 00:00:00').getTime();, since more milliseconds have now elapsed.

    It therefore follows that countDate - now is negative.

    To fix this, either change your code to now - countDate (which will return a positive number for a date in the past) or choose a date in the future for your countdown.

    Login or Signup to reply.
  3. The problem is the line gap = countDate - now;

    The now date is later than the countDate, therefore it’s internally represented as a larger number than countDate. To fix this, simply reverse the order of the subtraction:

    gap = now - countDate;

    Login or Signup to reply.
  4. It is because your countdate is less than the current date.
    You are counting from 1 apr 2023 but today is 15 apr 2023 , Hence the date is already over you need to keep your countdate greater than today’s date [i.e countdate > 15 apr] or you can change gap=now-Countdate

    Login or Signup to reply.
  5. Your countdate is set to past, so it will return negative value. I made this codepen to add a validation when it finished the countdown, it will return day:00, hour:00, minute:00 and second:00 as ypu can see it will 00. Try to change the countdate(example: April 17, 2023) to see the result.

    [Codepen.](https://codepen.io/neyubee/pen/OJBMBYj)
    
    Login or Signup to reply.
Please signup or login to give your own answer.
Back To Top
Search