javascript new Date(0)class显示16个小时?

时间:2010-04-09 02:13:27

标签: javascript date

interval = new Date(0);
return interval.getHours();

以上返回16.我希望它返回0.任何指针? getMinutes()和getSeconds()按预期返回零。谢谢!

我正在尝试制作一个计时器:

function Timer(onUpdate) {
    this.initialTime = 0;
    this.timeStart = null;

    this.onUpdate = onUpdate

    this.getTotalTime = function() {
        timeEnd = new Date();
        diff = timeEnd.getTime() - this.timeStart.getTime();

        return diff + this.initialTime;
    };

    this.formatTime = function() {
        interval = new Date(this.getTotalTime());

        return this.zeroPad(interval.getHours(), 2) + ":" +  this.zeroPad(interval.getMinutes(),2) + ":" + this.zeroPad(interval.getSeconds(),2);
    };

    this.start = function() {
        this.timeStart = new Date();
        this.onUpdate(this.formatTime());
        var timerInstance = this;
        setTimeout(function() { timerInstance.updateTime(); }, 1000);
    };

    this.updateTime = function() {
        this.onUpdate(this.formatTime());
        var timerInstance = this;
        setTimeout(function() { timerInstance.updateTime(); }, 1000);
    };

    this.zeroPad = function(num,count) {
        var numZeropad = num + '';
        while(numZeropad.length < count) {
            numZeropad = "0" + numZeropad;
        }
        return numZeropad;
    }
}

除了16小时的差异外,一切正常。有什么想法吗?

1 个答案:

答案 0 :(得分:6)

如果您将Date初始化为0,则会将其设置为1970年1月1日00:00:00 GMT时代的开头。你得到的时间是局部时间偏移。

要制作计时器,您宁愿从当前时间戳开始,并稍后计算它的差异。请记住,时间戳是绝对时间点,而不是相对时间。

var start = new Date();

// Time is ticking, ticking, ticking...

var end = new Date();

alert(end - start);

或者,更具体:

var start = new Date();

setTimeout(function () {
    var end = new Date();
    alert(end - start);
}, 2000);