我的倒数计时器会有任何问题吗?

时间:2018-05-02 15:58:16

标签: javascript

这个倒计时器的代码来自W3Schools:

// Set the date we're counting down to
var d = new Date();
var n = d.getTimezoneOffset() * 60000;

var countDownDate = new Date("May 2, 2018 15:54:25").getTime();

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

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

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

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

它有一个很大的问题:我输入的任何日期都不适用于不同的时区,就好像它是+1小时的UTC它会过期,如果它是-1,它将是一个小时。

所以我添加了d.getTimezoneOffset() * 60000;以获得毫秒差异,然后将其取下,所以如果有任何差异,它应该计算它。

如果我将来使用UTC日期,或者是否存在我不了解的可能差异(例如特殊国家或夏令时可能会弄乱它),它是否总是有效?

0 个答案:

没有答案