使用自定义日期时时间 returns 始终为 0

Time returns always 0 when using a custom date

我需要从开始日期开始计时 n 天。当我在设置间隔函数中使用日期(现在)时它可以工作但是如果我使用参数中的日期那么时间总是 0.

let startDate = new Date().getTime();

startTimer(days,startDate) {

  let today = new Date().getTime();
  let countDown = this.addDays(today,days);
  let countDown2 = new Date(countDown).getTime();

  let x = setInterval(() => {

  let now = new Date().getTime();
  //let distance = countDown2 - startDate; //not working when i use startDate here
  let distance = countDown2 - now; //working when i use 'now'
  let hours = Math.floor((distance % (1000 * 60 * 60 * 24)) / (1000 * 60 * 60));
  this.displayDate = hours + "h";

  if(distance < 0) {
    clearInterval(x);
    this.displayDate = "Expired";
     }
   })    
}

  addDays(date, days) {
   var result = new Date(date);
   result.setDate(result.getDate() + days);
  return result;
 }

当我将 startDate 用作参数中的 10 时,o/p 为 10d: 0h: 0m: 0s(时间始终为 0)

当我在 o/p 的 setinterval 时间内使用除现在以外的任何日期时,将是 0,比如 10d: 0h: 0m: 0s

删除间隔上x的初始值,并确保在间隔结束时添加一个时间间隔...

setInterval(() =>

// end of interval
}, 1000) // 1000ms = 1 second

并且该函数需要 return 某些东西......在这个例子中,我将 return 包含在 console.log() 中只是为了可视化它,但删除它很容易。

if(distance < 0) {
  clearInterval(x);
  return console.log("Expired")   
} else {
  return console.log(count_days + "d: " + hours + "h: " + minutes + "m: " + seconds + "s")
}  

进行这些更改后,您应该可以调用 startTimer() 函数,它应该可以正常工作...

startTimer(10, startDate)

/* OUTPUT
9d: 23h: 59m: 58s
9d: 23h: 59m: 57s
9d: 23h: 59m: 56s
9d: 23h: 59m: 55s
9d: 23h: 59m: 54s
*/