interval = new Date(0);
return interval.getHours();
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;
}
}
It all works fine except for the 16 hour difference. Any ideas?
If you initialize the
Datewith 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.
Or, more concrete: