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 小时的差异外,一切都很好。有任何想法吗?
如果您初始化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);
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)