javascript new Date(0)类显示16小时? [英] javascript new Date(0) class shows 16 hours?
问题描述
interval = new Date(0);
return interval.getHours();
以上返回16。我希望它返回0。是否有指针? getMinutes()和getSeconds()返回预期的零。谢谢!
The above returns 16. I expect it to return 0. Any pointers? getMinutes() and getSeconds() return zero as expected. Thanks!
我正在尝试创建计时器:
I am trying to make a timer:
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小时时差外,其他所有方法都可以正常工作。有任何想法吗?
It all works fine except for the 16 hour difference. Any ideas?
推荐答案
如果将 Date
初始化为0,它将将设置为新纪元的开始(格林尼治标准时间1970年1月1日00:00:00)。获得的小时数是本地化的时间偏移量。
If you initialize the Date
with 0, it will be set to the beginning of the epoch, Jan 1st 1970 00:00:00 GMT. The hours you get is the localized time offset.
要制作计时器,您宁愿先使用当前时间戳记,然后再计算其时差。请记住,时间戳记是绝对时间点,而不是相对时间点。
To make a timer, you'd rather start with the current timestamp and calculate the difference to it later on. Remember that timestamps are absolute points in time, not relative.
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);
这篇关于javascript new Date(0)类显示16小时?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!