I'm having an issue making this countdown, it shows more hours than "23". Any idea how to fix it?
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600);
var minutes = Math.floor((sec_num - (hours * 3600)) / 60);
var seconds = sec_num - (hours * 3600) - (minutes * 60);
return days " days" " : " hours " hrs" " : " minutes " min" " : " seconds " sec";
};
let startTime = 1649303300; // database unix-timestamp value
setInterval(() => {
let curTime = (new Date()).getTime() / 1000;
curTime = parseInt(curTime);
if (curTime < startTime){
document.getElementById("timer1").innerText = ("LAUNCHING IN:");
document.getElementById("timer").innerText = (`${startTime-curTime}`).toHHMMSS();
}
else {
document.getElementById("timer1").innerText = ("LAUNCHED");
document.getElementById("timer").innerText = ("");
}
}, 1000);
"
I'm getting more than "23" for the "hours" variable instead of increasing the days every 24 hours.
CodePudding user response:
You're not subtracting the days from the hours
variable in the way that you're doing it for minutes
and seconds
. Try declaring your hours variable like this:
var days = Math.floor(sec_num / 86400);
var hours = Math.floor((sec_num - (days * 86400)) / 3600);
You can also use modular arithmetic to strip the excess values. You can use the modulo operator for this, e.g.
String.prototype.toHHMMSS = function() {
var sec_num = parseInt(this, 10);
var days = Math.floor(sec_num / 86400);
var hours = Math.floor(sec_num / 3600) % 24;
var minutes = Math.floor(sec_num / 60) % 60;
var seconds = sec_num % 60;
return days " days" " : " hours " hrs" " : " minutes " min" " : " seconds " sec";
};