Similar to "This site has been accident-free for x days," the number would increase automatically every day. I'm ok with entering a starting number or the date from which I want to count. Also like a reverse countdown. Thanks in advance!
CodePudding user response:
You can do something like this:
function getAccidentFreeDays() {
const dateThen = new Date('11/17/2021'); // enter the accident free day
const dateNow = new Date(); // gets todays date
const diff = dateThen.getTime() - dateNow.getTime(); // get the difference between the date then and the date now
const days = Math.ceil(diff / (1000 * 3600 * 24)); // converts the milliseconds to days
return days;
}
CodePudding user response:
You can use
function sleep(milliseconds) {
var start = new Date().getTime();
for (var tik = 0; tik < 1e7; tik ) {
if ((new Date().getTime() - start) > milliseconds){
break;
}
}
}
var counter = 0;
while (true) {
sleep(86400000);
counter ;
}
/* Whatever you have here */
<!DOCTYPE HTML>
<html>
<!-- whatever you have here -->
<body>
<!-- whatever you have here -->
<script src="/script.js"></script>
</body>
</html>
<iframe name="sif1" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>
I found a good way to add sleeping (a.k.a waiting) into JS and then converted days to milliseconds (quite a lot to do), so you can insert sleep with the milliseconds from a day, and then add counter. You can then insert counter into your tag represented with x.
CodePudding user response:
Get the start date and minus it from the current date, then get the difference.
Using JavaScript
const date1 = new Date('11/18/2021');
const date2 = new Date();
const diffTime = Math.abs(date2 - date1);
const diffDays = Math.round(diffTime / (1000 * 60 * 60 * 24));
document.getElementById('x').innerHTML = diffDays;
<div>This site has been accident-free for <span id="x"></span>day(s)
<iframe name="sif2" sandbox="allow-forms allow-modals allow-scripts" frameborder="0"></iframe>