所以这是我第一次使用Moment.js,我遇到了以下问题,所以我有以下日期:
now: 2017-01-26T14:21:22+0000 expiration: 2017-01-29T17:24:22+0000
我想得到的是:
Day: 3 Hours: 3 Mins: 3
我尝试了以下代码:
const now = moment(); const exp = moment(expire_date); console.log(expire_date); days = exp.diff(now, 'days'); hours = exp.diff(now, 'hours') - (days * 24); minutes = exp.diff(now, 'minutes') - ((days * 1440) + (hours * 24) * 60);
我知道我做错了(也许是我的计算或者我使用了错误的方法),但我无法弄清楚它是什么.
MomentJS可以为您计算所有这些,而无需您做任何逻辑.
首先找出两个时刻之间的区别
将其表示为持续时间
然后显示任何组件中.days()
,.hours()
所需的持续时间.
注意:如果需要.asDays()
,您还可以表达整个持续时间.asHours()
等.
const now = moment("2017-01-26T14:21:22+0000");
const expiration = moment("2017-01-29T17:24:22+0000");
// get the difference between the moments
const diff = expiration.diff(now);
//express as a duration
const diffDuration = moment.duration(diff);
// display
console.log("Days:", diffDuration.days());
console.log("Hours:", diffDuration.hours());
console.log("Minutes:", diffDuration.minutes());