Momentjs倒计时-持续时间显示为负数

时间:2018-09-05 16:59:04

标签: javascript typescript rxjs momentjs countdown

我正试图用MomentJS(2.22.2)和Rxjs(6.2.2interval创建倒计时。但是,当我到达某个时间点时,我的倒计时就会变得疯狂并输出负数,例如,它应该减去一天并从23小时开始。

有关如何解决此问题的任何帮助吗?


示例

当地时间:2018-09-05T18:49

结束时间:2018-11-03T18:00

这导致:

Negative countdown


我的代码

'this.days','this.hours','this.minutes'和'this.seconds'是局部变量,它们以字符串形式表示结果时间(字符串格式,因为我想显示前导零)

interval(1000).subscribe(() => {
      const now = moment();
      let timeLeft = this.endDate.diff(now, 'milliseconds', true);
      let endDate = moment(this.endDate); // Use 'moment' to make a new copy

      // Days
      const days = Math.floor(moment.duration(timeLeft).asDays());
      console.warn(moment.duration(timeLeft).asDays());
      this.days = Countdown.addLeadingZeros(days.toString(), 3);

      endDate = endDate.subtract(days, 'days');
      timeLeft = endDate.diff(now, 'milliseconds', true);

      // Hours
      const hours = Math.floor(moment.duration(timeLeft).asHours());
      console.warn(Math.round(moment.duration(timeLeft).asHours()));
      this.hours = Countdown.addLeadingZeros(hours.toString(), 2);

      endDate = endDate.subtract(hours, 'hours');
      timeLeft = endDate.diff(now, 'milliseconds', true);

      // Minutes
      const minutes = Math.floor(moment.duration(timeLeft).asMinutes());
      this.minutes = Countdown.addLeadingZeros(minutes.toString(), 2);

      endDate = endDate.subtract(minutes, 'minutes');
      timeLeft = endDate.diff(now, 'milliseconds', true);

      // Seconds
      const seconds = Math.floor(moment.duration(timeLeft).asSeconds());
      this.seconds = Countdown.addLeadingZeros(seconds.toString(), 2);
});

有人看到我在这里做错了什么,或者我如何改进此代码?

1 个答案:

答案 0 :(得分:2)

由于夏时制的更改,代码中出现负数。

在英国,夏令时在2018-09-052018-11-03之间发生了变化。实际上它在2018-10-28上。如果我在任一侧选择两个日期,则可以重现您的问题,但如果两个日期都在同一侧,则不能。我猜想您居住的地方,夏令时也在2018-09-052018-11-03之间变化。

避免此类问题的最简单方法是使用UTC中的时间计算时间差。不用写

  const now = moment();

  const now = moment().utc();

并确保this.endDate是在UTC而非本地时间创建的。

相关问题