barnade95
barnade95

Reputation: 109

JS countdown show days in hours

I have this countdown script that counts down until 2018 now. It shows hours, minutes, secs. I want it to show the remaining days also in hours. For example, 2 days before the end of the countdown it should show 48:00:00. I can't really dig in the math part, can you please help me with this?

var countDownDate = new Date("Jan 01, 2018 00:00:00").getTime();
var x = setInterval(function() {
  var now = new Date().getTime();
  var distance = countDownDate - now;
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  document.getElementById("demo").innerHTML = ('0' + hours).slice(-2) + " : " +
    ('0' + minutes).slice(-2) + " : " + ('0' + seconds).slice(-2);
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "BÚÉK 2018";
  }
}, 1000);
<div id="demo"></div>

Upvotes: 0

Views: 617

Answers (1)

Peter B
Peter B

Reputation: 24147

All you need to do is add 24 * days to the hours amount.

With a further small change to no longer show hours as a 2-digit number, this is what results:

var countDownDate = new Date("Jan 01, 2018 00:00:00").getTime();
var x = setInterval(function() {
  var now = new Date().getTime();
  var distance = countDownDate - now;
  var days = Math.floor(distance / (1000 * 60 * 60 * 24));
  var hours = 24 * days + Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  var minutes = Math.floor((distance % (1000 * 60 * 60)) / (1000 * 60));
  var seconds = Math.floor((distance % (1000 * 60)) / 1000);
  document.getElementById("demo").innerHTML = hours + " : " +
    ('0' + minutes).slice(-2) + " : " + ('0' + seconds).slice(-2);
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "BÚÉK 2018";
  }
}, 1000);
<div id="demo"></div>

Upvotes: 2

Related Questions