0

我在 StackOverFlow 上找到了这段 Javascript,它显示了特定日期的实时倒计时。

<script>
var end = new Date('02/19/2012 10:1 AM');

    var _second = 1000;
    var _minute = _second * 60;
    var _hour = _minute * 60;
    var _day = _hour * 24;
    var timer;

    function showRemaining() {
        var now = new Date();
        var distance = end - now;
        if (distance < 0) {

            clearInterval(timer);
            document.getElementById('countdown').innerHTML = 'EXPIRED!';

            return;
        }
        var days = Math.floor(distance / _day);
        var hours = Math.floor((distance % _day) / _hour);
        var minutes = Math.floor((distance % _hour) / _minute);
        var seconds = Math.floor((distance % _minute) / _second);

        document.getElementById('countdown').innerHTML = days + ' Days ';
        document.getElementById('countdown').innerHTML += hours + ' Hours ';
        document.getElementById('countdown').innerHTML += minutes + ' Minutes ';
        document.getElementById('countdown').innerHTML += seconds + ' Seconds';
    }

    timer = setInterval(showRemaining, 1000);
</script>
<div id="countdown"></div>

但是,我想让它使用的时间是 EST。因此,如果人们从不同时区查看计数器,他们会看到相同的东西。我怎样才能做到这一点?我是 JavaScript 新手,我不知道从哪里开始。

4

1 回答 1

0

这会起作用:

<script>
var end = new Date('02/19/2012 10:1 AM EST');

var _second = 1000;
var _minute = _second * 60;
var _hour = _minute * 60;
var _day = _hour * 24;
var timer;

function getESTOffset() {

    return new Date().getTimezoneOffset() - (end.getTimezoneOffset())
}

function showRemaining() {
    var now = new Date();
    var distance = end - now - getESTOffset() * _hour;
    if (distance < 0) {

        clearInterval(timer);
        document.getElementById('countdown').innerHTML = 'EXPIRED!';

        return;
    }
    var days = Math.floor(distance / _day);
    var hours = Math.floor((distance % _day) / _hour);
    var minutes = Math.floor((distance % _hour) / _minute);
    var seconds = Math.floor((distance % _minute) / _second);

    document.getElementById('countdown').innerHTML = days + ' Days ';
    document.getElementById('countdown').innerHTML += hours + ' Hours ';
    document.getElementById('countdown').innerHTML += minutes + ' Minutes ';
    document.getElementById('countdown').innerHTML += seconds + ' Seconds';
}

timer = setInterval(showRemaining, 1000);
</script>
<div id="countdown"></div>

这里的关键是将结束设置在您希望它所在的时区(EST)中,并在计算之前使用它的偏移量。

于 2014-06-06T17:28:42.450 回答