Home > Back-end >  How to set a global 24 hour countdown timer so all users see the exact same remaining hours?
How to set a global 24 hour countdown timer so all users see the exact same remaining hours?

Time:05-09

I have a countdown timer that I'd like to show the exact same amount of remaining hours and minutes for every user regardless of timezone or location (days aren't important).

I'm assuming I need to target and output UTC somehow. Will I have any daylight-saving problems with this? The actual end time is not very important. Everyone seeing the same remaining time is.

I've researched similar posts here but they're a few years old and didn't find answers. Hoping a solution or newer approach is available. All programming languages considered.

// Set the date we're counting down to
var countDownDate = new Date("May 10, 2022 24:00:00").getTime();

// Update the count down every 1 second
var x = setInterval(function() {

  // Get today's date and time
  var now = new Date().getTime();

  // Find the distance between now and the count down date
  var distance = countDownDate - now;

  // Time calculations for days, hours, minutes and seconds
  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);

  // Output the result in an element with id="demo"
  document.getElementById("demo").innerHTML = days   "d "   hours   "h "  
    minutes   "m "   seconds   "s ";

  // If the count down is over, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("demo").innerHTML = "EXPIRED";
  }
}, 1000);
#demo {
  font: normal 20px arial
}
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.3.1/jquery.min.js"></script>
<div id="demo"></div>

https://jsfiddle.net/r64zp93c/

CodePudding user response:

It seems Date.UTC() is what you're looking for. From the docs:

The Date.UTC() method accepts parameters similar to the Date constructor, but treats them as UTC. It returns the number of milliseconds since January 1, 1970, 00:00:00 UTC.

So instead of

var countDownDate = new Date("May 10, 2022 24:00:00").getTime();

You should be able to do

var countDownDate = Date.UTC(2022, 4, 10, 24, 0, 0);

(But maybe adjust the hours/day to UTC to match the specific time you need)

  • Related