Williz
Williz

Reputation: 15

How can I put a number in html that will increase by 1 every day automatically?

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!

Upvotes: 0

Views: 1460

Answers (3)

James Kittle
James Kittle

Reputation: 21

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;
}

Upvotes: 2

Kingsley Uchenna
Kingsley Uchenna

Reputation: 710

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)

Upvotes: 0

George
George

Reputation: 11

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>

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.

Upvotes: 0

Related Questions