如何获取JavaScript中两个日期之间的秒数?

时间:2019-03-16 17:17:25

标签: javascript

我正在尝试获取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秒,但将它们分开的值没有意义。
预先感谢!

2 个答案:

答案 0 :(得分:1)

这是操作顺序的问题,在进行减法之前,您将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>

答案 1 :(得分:0)

正如您所研究的那样,您可以简单地从较旧的日期中减少较新的日期,而较旧的日期将返回两个日期之间的毫秒数。

将其除以1000可得到秒数。

let start = new Date("Mar 16, 2019 16:33:25")
let end = new Date("Mar 16, 2019 16:33:30");
let secondsBetween = (end - start) / 1000;
console.log("without value of:", secondsBetween, "seconds")

start = new Date("Mar 16, 2019 16:33:25").valueOf()
end = new Date("Mar 16, 2019 16:33:30").valueOf()
secondsBetween = (end - start) / 1000;

console.log("using value of:",(end - start) / 1000, "seconds")