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)
tried to rectify the code but unable to understand it fully, kindly help what needs to be done in this
5
Answers
The countDate variable is set to a date and time in the past
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 thannew 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.The problem is the line
gap = countDate - now;
The
now
date is later than thecountDate
, therefore it’s internally represented as a larger number thancountDate
. To fix this, simply reverse the order of the subtraction:gap = now - countDate;
It is because your countdate is less than the current date.
You are counting from
1 apr 2023
but today is15 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 changegap=now-Countdate
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.