interval = new Date(0);
return interval.getHours();
Run Code Online (Sandbox Code Playgroud)
以上返回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;
}
}
Run Code Online (Sandbox Code Playgroud)
除了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);
Run Code Online (Sandbox Code Playgroud)
或者,更具体:
var start = new Date();
setTimeout(function () {
var end = new Date();
alert(end - start);
}, 2000);
Run Code Online (Sandbox Code Playgroud)