使用 x.fromNow() 获取 moment.js 中的天数;

Get number of days as number in moment.js with x.fromNow();

我用Moment.js

var created = moment("24.07.2015 16:09:05", "DD.MM.YYYY hh:mm:ss");
var expire= created.add(7, 'days');
var countdown = expire.fromNow();

var countdown 给了我字符串 "in 3 days" - 但是如果没有字符串 "in days",我怎么能只得到几天或几小时的数字呢? 当倒计时小于 7 天、4 天或 1 天时,我想进行比较并用不同颜色标记倒计时。

使用moment.duration:

var created = moment("24.07.2015 16:09:05", "DD.MM.YYYY hh:mm:ss");
var expires = created.clone().add(7, 'days');

var now = new Date;
var dur = moment.duration({ from: now, to: expires });

console.log(dur.humanize()); // => "3 days"
console.log(dur.asDays()); // => 3.0729382175925926

这正是 fromNow 所做的 behind the scenes。您可以将任何日期或时刻对象用于 fromto 选项,因此,例如你想得到现在和 expires 之间的时间,你会做 moment.duration({ from: new Date, to: expires }).