【问题标题】:javascript new Date(0) class shows 16 hours?javascript new Date(0) 类显示 16 小时?
【发布时间】:2010-04-09 10:44:58
【问题描述】:
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 小时的差异外,一切正常。有什么想法吗?

【问题讨论】:

    标签: javascript date


    【解决方案1】:

    如果您使用 0 初始化 Date,它将被设置为纪元的开始,即 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);
    

    【讨论】:

    • 嗯.. 看看我对我的问题的编辑。我可能走错路了
    • 这就是我所做的。但差异为零,new Date(0) 报告 16 小时。我认为问题在于 getHours() 返回当天的小时数,而不是转换为小时的 unix 时间戳(这有意义吗?)
    • @Jonah 没错。在上面的示例中,差异很可能是 0,因为它是立即执行的。 time is ticking... 意味着您需要在两者之间做一些事情,end 将在稍后的某个时间创建。在浏览器的控制台中输入此示例,您将看到不同之处。
    • @Jonah getHours() 确实返回了时间戳Dec 31st 1969, 16:00:00(本地化)的绝对时间,即下午4点。
    • 好的,所以我需要一种将毫秒转换为小时、分钟和秒的方法。现在工作..(getHours() 不起作用,使用不同的方式)谢谢!
    猜你喜欢
    • 2022-06-17
    • 2020-08-23
    • 1970-01-01
    • 2015-08-16
    • 2013-04-10
    • 2020-02-03
    • 1970-01-01
    • 1970-01-01
    • 2013-05-05
    相关资源
    最近更新 更多