gpt4 book ai didi

javascript - 如何在javascript中获取两个日期之间的秒数?

转载 作者:行者123 更新时间:2023-12-03 00:00:28 25 4
gpt4 key购买 nike

我正在尝试获取 javascript 中两个日期之间的秒数。
问题 herehere建议一个简单的减法操作就可以解决问题,其他答案建议您使用 .getTime().valueOf() 属性。
但尽管如此,当我减去相隔 5 秒的两个日期时,我得到的值 1551181475795 太大了,无法正确。
这是我的代码:

var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");

// Find the distance between now and the count down date
var distance = Math.abs(now - countDownDate / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;

// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id='demo'>

正如您所见,两个时间仅相差 5 秒,但分隔它们的值没有任何意义。
提前致谢!

最佳答案

这是一个运算顺序问题,在进行减法之前,您需要将 countDownDate 除以 1000(您正在计算 now - countDownDate/1000 但是,您应该计算 (now - countDownDate)/1000,先减法):

var countDownDate = new Date("Mar 16, 2019 16:33:25").valueOf();
var dist = 347155200;
// Update the count down every 1 second
var x = setInterval(function() {

// Get todays date and time
var now = new Date("Mar 16, 2019 16:33:30");

// Find the distance between now and the count down date
var distance = Math.abs((now - countDownDate) / 1000);
// Display the result in the element with id="demo"
document.getElementById("demo").innerHTML = distance;

// If the count down is finished, write some text
if (distance < 0) {
clearInterval(x);
document.getElementById("demo").innerHTML = "EXPIRED";
}
}, 1000);
<p id="demo"></p>

关于javascript - 如何在javascript中获取两个日期之间的秒数?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/55199454/

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