终端输出:
Now: { _d: Sat Jan 13 2018 02:39:25 GMT-0400 (AST),_isUTC: false,_a: null,_lang: false }
Expiration Date: { _d: Wed Feb 13 2013 02:00:15 GMT-0400 (AST),_lang: false }
Difference between Now and Expiration Date: NaN
码:
console.log('Difference between Now and Expiration Date:',now.diff(expDate,'months',true));
moment.js来源:
diff : function (input,val,asFloat) {
var inputMoment = this._isUTC ? moment(input).utc() : moment(input).local(),zoneDiff = (this.zone() - inputMoment.zone()) * 6e4,diff = this._d - inputMoment._d - zoneDiff,year = this.year() - inputMoment.year(),month = this.month() - inputMoment.month(),date = this.date() - inputMoment.date(),output;
if (val === 'months') {
output = year * 12 + month + date / 30;
} else if (val === 'years') {
output = year + (month + date / 30) / 12;
} else {
output = val === 'seconds' ? diff / 1e3 : // 1000
val === 'minutes' ? diff / 6e4 : // 1000 * 60
val === 'hours' ? diff / 36e5 : // 1000 * 60 * 60
val === 'days' ? diff / 864e5 : // 1000 * 60 * 60 * 24
val === 'weeks' ? diff / 6048e5 : // 1000 * 60 * 60 * 24 * 7
diff;
}
return asFloat ? output : round(output);
}
最佳答案
从问题的评论中,我收集到您试图将一个实例直接存储到MongoDB中,然后再检索它.
原文链接:https://www.f2er.com/js/429689.html片刻不能直接序列化,所以这总会导致问题.您应该从此刻获得ISO字符串:
var m = moment();
var s = m.toISOString(); // "2013-08-02T20:13:45.123Z"
将该字符串存储在MongoDB中.稍后,当您检索它时,您可以从该值构造新的时刻实例.
var m = moment("2013-08-02T20:13:45.123Z");
如果你喜欢更紧凑的东西,你可以使用从m.valueOf()获得的数字.但这并不像阅读或操纵那么容易.
请勿使用评论中建议的_d字段.这是内在的,不应该直接使用.它可能不是你所期望的.