Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

javascript new Date(0) class shows 16 hours?

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?

like image 459
Jonah Avatar asked Apr 09 '10 02:04

Jonah


1 Answers

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);

Or, more concrete:

var start = new Date();

setTimeout(function () {
    var end = new Date();
    alert(end - start);
}, 2000);
like image 127
deceze Avatar answered Sep 20 '22 12:09

deceze