javascript new Date(0) 类显示 16 小时?

标签 javascript date

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。您获得的小时数是本地化时间偏移量。

要制作计时器,您宁愿从当前时间戳开始,然后计算与它的差异。请记住,时间戳是绝对时间点,而不是相对时间点。

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

关于javascript new Date(0) 类显示 16 小时?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2604708/

相关文章:

javascript - 如何为 session 存储正确设置 redis

javascript - 将不同的功能附加到动态创建的卡片

php - 使用 date_i18n 格式化 WooCommerce 传递消息的日期

java - Liquibase 将列类型从日期更改为日期时间而不删除包含的值

javascript - Webdriver.io 比较运算符

javascript - 等待循环中的每个动画完成后再运行下一个动画

javascript - 使用 NodeJS 读取 XML 托管文件

mysql - 从mysql表的日期属性中获取月份和日期值

javascript - 正则表达式如何匹配日期时间字符串特定字符的前2个实例

GWT 日期处理...让客户端尊重服务器的时区