倒数计时器-时区问题

时间:2018-09-06 22:35:54

标签: javascript time timer timezone var

我正在关注本教程:https://www.w3schools.com/howto/howto_js_countdown.asp

除时区外,其他所有东西都可以正常工作,我希望它在UTC中的每个设备上显示相同的时间,无论时区如何。我该怎么办?

如果某个时区的某人比我领先,他们会看到不同的时间(因为他们提前了一个小时,所以倒数计时将在另一个时间结束。对于他们来说,倒计时将在结束时间之前一个小时结束)我,我希望在计时器上的相同时间到处显示

代码(已编辑):

function convertDateToUTC(date) {
  return new Date(date.getUTCFullYear(), date.getUTCMonth(), date.getUTCDate(), date.getUTCHours(), date.getUTCMinutes(), date.getUTCSeconds());
}

function getUTCNow() {
  var now = new Date();
  var time = now.getTime();
  var offset = now.getTimezoneOffset();
  offset = offset * 60000;
  return time - offset;
}
// Set the date we're counting down to
//var countDownDate = new Date("Sep 15, 2018 15:00:00").getTime();
var countDownDate = new Date("Sep 7, 2018 20:00:00");
var countDD = convertDateToUTC(countDownDate);

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

  // Get todays date and time
  var now = new Date();
  var nowUTC = now.getUTCTime();

  // Find the distance between now and the count down date
  var distance = countDD.getTime() - nowUTC.getTime();

  // 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);

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

  // If the count down is finished, write some text 
  if (distance < 0) {
    clearInterval(x);
    document.getElementById("timer").innerHTML = "RELEASED!";
  }
}, 1000);
<div id="timer"></div>

0 个答案:

没有答案