0

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>
j08691
  • 204,283
  • 31
  • 260
  • 272
barnade95
  • 109
  • 1
  • 2
  • 7
  • Well, almost all the time a day has 24 hours, so if you multiply those days by 24 and then add it to the hours, maybe that could work? – William-H-M Dec 26 '17 at 21:59
  • `new Date("Jan 01, 2018 00:00:00")` uses the built-in parser, which is a bad idea (see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results)). If you want a date for new year on the host, pass values directly to the Date constructor (which is also less to type): `new Date(2018, 0)`. – RobG Dec 26 '17 at 22:15

1 Answers1

2

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>
Peter B
  • 22,460
  • 5
  • 32
  • 69