Search code examples
javascripthtmlcountdownclockcountdowntimer

Javascript countdown that is the same for people in every region


Currently I have a countdown timer, the only problem is that I entered a date and time that doesn't end at the same time as people that live elsewhere, will have the javascript interpreted to their timezone. Is there a way I can fix this? Current script:

var countDownDate = new Date("Jul 30, 2020 20: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("countdown").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";


  if (distance < 0) {
    clearInterval(x);
    document.getElementById("countdown").innerHTML = "EXPIRED";
  }
}, 1000);
<p id="countdown"></p>


Solution

  • Add an explicit timezone to your string (eg. UTC-0000)

    // Add an explicit timezone to your string (eg. UTC-0000)
    var countDownDate = new Date("Jul 30, 2020 20:00:00 UTC-0000").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("countdown").innerHTML = days + "d " + hours + "h "
      + minutes + "m " + seconds + "s ";
    
    
      if (distance < 0) {
        clearInterval(x);
        document.getElementById("countdown").innerHTML = "EXPIRED";
      }
    }, 1000);
    <p id="countdown"></p>