gpt4 book ai didi

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

转载 作者:塔克拉玛干 更新时间:2023-11-02 20:29:00 26 4
gpt4 key购买 nike

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/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com