【问题标题】:Momentjs countdown - Duration is showing negative numbersMomentjs 倒计时 - 持续时间显示负数
【发布时间】:2018-09-05 16:59:04
【问题描述】:

我正在尝试使用 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);
});

有没有人看到我在这里做错了什么或者我可以如何改进这段代码?

【问题讨论】:

    标签: javascript typescript rxjs momentjs countdown


    【解决方案1】:

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

    在英国,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 而不是本地时间创建的。

    【讨论】:

    • 在这些日期内确实设置了夏令时(可能不再!independent.co.uk/news/world/europe/…)无论如何,您将如何“恢复”UTC日期? moment.utc().toISODate() 给我:2018-09-05T22:45:00.890Z。但是当我执行moment(<date>) 或moment().utc(<date>) 时,我会收到一个已弃用的警告
    • @Mr.wiseguy:对我来说,moment("2018-09-05T22:45").utc().format() 打印出2018-09-05T21:45:00Z。我无法重现弃用警告:是否可以列出您在编写 <date> 时使用的确切字符串?也不清楚你所说的“复活”是什么意思 - 你能解释更多吗?
    • 我正在做moment().utc().toISODate() 并通过moment(<iso-string>).utc() 恢复字符串,我应该为字符串做moment().utc().format() 和moment(<date>).utc() 一会儿约会。现在可以了。非常感谢!
    猜你喜欢
    • 1970-01-01
    • 2013-01-06
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2018-11-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多