I have a setInterval
that shows the current date and time, and now I am extending the code so it will also display the percentage of progress in the calendar year. At the time of writing we are at 29%. This calculation works fine (see the final
variable below). My question is:
How to get the time that is left until that percentage becomes 30%? And once we arrive at that point: the time left until it becomes 31%, …etc?
I know that a percentage increment happens on this scale roughly every three and half days, exactly 87.5 hours.
Here is my code:
setInterval(function () {
const dt = new Date();
document.getElementById("datetime").innerHTML =
("0" + dt.getDate()).slice(-2) +
"." +
("0" + (dt.getMonth() + 1)).slice(-2) +
"." +
dt.getFullYear() +
" " +
("0" + dt.getHours()).slice(-2) +
":" +
("0" + dt.getMinutes()).slice(-2) +
":" +
("0" + dt.getSeconds()).slice(-2)
}, 1);
const start = new Date(2023,12,1);
const end = new Date(2024,12,1);
const today = new Date();
const total = end - start;
let progress = today - start;
const final = Math.round(progress / total * 100 ) + "%"
const finalCalc = document.querySelector("#percentage")
finalCalc.innerHTML = final;
Current time: <span id="datetime"></span><br>
Progress: <span id="percentage"></span><br>
Until next %-increment: <span id="remaining">?</span>
The output I would like to see added and keep updated would be for example:
the next percentage increment will occur in xxx amount of hours
How can I achieve that?
3
Answers
You can do this calculation using the millisecond values of the dates
(I’ll let you refine this calculation according to your time zone.)
Below, is a refactorisation of your code, with some newly added functions, to improve readability. Also, this new code updates all stats every ms, and not just the current time, as you had in your question:
Though I have added comments throughout the code, don’t hesitate to ask if something feels off!!!
Hope this helped! And may the code be with you…
First of all, realise that
new Date(2024,12,1)
is the same asnew Date(2025,0,1)
, as the month argument is zero-based.Secondly, I would not use
round
in your percentage formula, as that would mean you’d hit 100% about two days before the target date. Usefloor
instead.You can take the percentage, add one and then reverse the formula to know at which time the percentage will increase with one unit.
Here is a snippet:
It will be hard to test the correctness like this, as it takes a long time before a percentage increase occurs, so maybe use two dates that are closer to each other to do that, like just 1 hour apart (the start of the current hour and the end of it):