gpt4 book ai didi

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

转载 作者:行者123 更新时间:2023-11-30 14:24:18 25 4
gpt4 key购买 nike

我正在尝试使用 MomentJS (2.22.2) 和 Rxjs (6.2.2) interval 创建倒计时。但是当我到达某些时间点时,我的倒计时变得疯狂并输出负数,例如,它应该减去一天并从 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);
});

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

最佳答案

由于夏令时的变化,您的代码中出现了负数。

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

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

  const now = moment();

  const now = moment().utc();

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

关于javascript - Momentjs 倒计时 - 持续时间显示负数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/52190158/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com