javascript - 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);
});
有谁看到我在这里做错了什么或如何改进这段代码?
解决方案
由于夏令时更改,您的代码中会出现负数。
在英国,夏令时在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 而不是本地时间创建的。
推荐阅读
- go - 如何验证来自中间件 go-gin 的数据
- java - 如何在 GraphQL Java 中覆盖 DataFetcherExceptionHandler?
- javascript - jqGrid filterToolbar 仅适用于某些列
- python - Pandas 相当于过滤器,后跟 dplyr 中的 groupby 函数
- automated-tests - 需要在 Cypress 中多次访问注册链接
- r - 如何在 RStudio 的工作目录/RProject 中使用多个数据源
- postgresql - 基于角色的数据库设计。作为用户属性或角色特定表的角色
- javascript - 我想在画布的各个方向重新缩放我的图像,但它只在右下角
- excel - 使用公式查找范围内具有零值的最后一行
- emacs - Emacs + Cider:无需输入首字母即可显示所有自动完成选项