如何在其他时区使用此倒数计时?

时间:2018-12-31 06:54:32

标签: javascript html

我正在设置一个新的倒计时(我知道有点晚),但是我想知道如何使它在其他时区工作

我已经将它用于通常的UTC时区,这就是默认值。我尝试过.toLocalString,它在倒计时中返回了NaN

var countDownDate = new Date("Dec 31, 2018 23:59:02").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("display").innerHTML = days + "d " + hours + "h "
  + minutes + "m " + seconds + "s ";

  if (distance < 0) {
    clearInterval(x);
    document.getElementById("display").innerHTML = "Happy New Year!";
    done()

  }
}, 1000);

2 个答案:

答案 0 :(得分:1)

javascript的Date函数返回每个时区的本地时间,具体取决于页面的加载位置。因此您不必跟踪每个时区 explained here

答案 1 :(得分:0)

您可以使用moment.js轻松实现这一目标:

var tz = moment.tz.guess();
console.log("Current Timezone: " + tz);
var last = moment.tz("2018-12-31 23:59:02", tz);
setInterval(function(){
    var current = moment.tz(tz);
    if(current.isBefore(last, "seconds")){
        var diff = moment.duration(last.diff(current));        
        document.getElementById("display").innerHTML = diff.days() + "d " + 
            diff.hours() + "h " + diff.minutes() + "m " + diff.seconds() + "s";
    }else{
        document.getElementById("display").innerHTML = "Happy New Year!";
    }
}, 1000);
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment.js/2.23.0/moment.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/moment-timezone/0.5.23/moment-timezone-with-data-2012-2022.min.js"></script>
<div id="display"></div>