0

How can I create a countdown to a specific date & time so that users anywhere in the world are counting down to the same UTC (or timezone) time.

This code below (from here at W3Schools.com) works for a general countdown but how can I add in the timezone aspect?

    <!DOCTYPE HTML>
<html>
<head>
<meta name="viewport" content="width=device-width, initial-scale=1">
<style>
p {
  text-align: center;
  font-size: 60px;
  margin-top: 0px;
}
</style>
</head>
<body>

<p id="demo"></p>

<script>
// Set the date we're counting down to
var countDownDate = new Date("Apr 20, 2021 20: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);
</script>

</body>
</html>
Jules
  • 13
  • 1
  • 5
  • `Date("Apr 20, 2021 20:00:00")` produces a date in UTC timezone. Is that what you want? – terrymorse Apr 20 '20 at 17:36
  • Ideally a location timezone rather than just UTC so that it can accommodate for daylight savings. E.g. I'd like to set it in British time so it's always counting down to a UK time, rather than just GMT/UTC as then it's out of date during daylight savings. – Jules Apr 20 '20 at 17:44
  • You might look at this timezone changer suggestion: https://stackoverflow.com/a/53652131/3113485 – terrymorse Apr 20 '20 at 17:54

1 Answers1

0

simply use yourDate.toLocaleString( ... => https://developer.mozilla.org/fr/docs/Web/JavaScript/Reference/Objets_globaux/Date/toLocaleString

list of Time Zone : https://en.wikipedia.org/wiki/List_of_tz_database_time_zones

sample code :

var countDownDate = new Date("Apr 20, 2021 20:00:00")

const timeOption = { hour12:true, timeZone:'UTC' };

console.log( countDownDate.toLocaleString("en-GB",  timeOption ) )
Mister Jojo
  • 20,093
  • 6
  • 21
  • 40