首页 > 解决方案 > Momentjs 倒计时 - 持续时间显示负数

问题描述

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

关于我应该如何解决这个问题的任何帮助?


例子

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

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

这导致:

负数倒计时


我的代码

' 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);
});

有谁看到我在这里做错了什么或如何改进这段代码?

标签: javascripttypescriptrxjsmomentjscountdown

解决方案


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

在英国,夏令时在2018-09-05和之间发生了变化2018-11-03。事实上它在2018-10-28. 如果我在这两侧选择两个日期,我可以重现您的问题,但如果两个日期都在同一侧,则无法重现。2018-09-05我猜你住的地方在和之间也有夏令时的变化2018-11-03

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

  const now = moment();

  const now = moment().utc();

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


推荐阅读