【发布时间】: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