为什么moment.js diff方法返回NaN?

6 javascript serialization mongodb momentjs

终端输出:

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),
      _isUTC: false,
      _a: null,
      _lang: false }
Difference between Now and Expiration Date: NaN
Run Code Online (Sandbox Code Playgroud)

码:

console.log('Difference between Now and Expiration Date:', now.diff(expDate, 'months', true));
Run Code Online (Sandbox Code Playgroud)

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);
        }
Run Code Online (Sandbox Code Playgroud)

Mat*_*int 5

从问题的评论中,我认为您正在尝试将moment实例直接存储到 MongoDB 中,然后稍后再检索。

Amoment不能直接序列化,所以这总是会导致问题。您应该从现在开始获取 ISO 字符串:

var m = moment();
var s = m.toISOString(); //  "2013-08-02T20:13:45.123Z"
Run Code Online (Sandbox Code Playgroud)

将该字符串存储在 MongoDB 中。稍后,当您检索它时,您可以从该值构造一个新的矩实例。

var m = moment("2013-08-02T20:13:45.123Z");
Run Code Online (Sandbox Code Playgroud)

如果你喜欢更紧凑的东西,你可以使用从中获得的数字m.valueOf()。但这并不容易阅读或操作。

不要使用_d评论中建议的字段。这是 moment 的内部,不应直接使用。它可能不是您所期望的。


Joh*_*ith 5

比较两个矩对象时,我遇到了同样的问题。我遇到的问题是,第一个时刻是指定英国日期格式构建的,而第二个时刻是在未指定英国日期格式的情况下创建的,并且日期恰好大于 12 日,例如当月 27 日。在调试时仔细检查,第二个日期的时刻对象注意到它的 _d 字段是一个无效的日期。

var startDate = moment("23/09/2019", "DD/MM/YYYY");
var endDate = moment("27/09/2019");
var dateDiff = startDate.diff(endDate, "days"); // returns NaN
Run Code Online (Sandbox Code Playgroud)

解决方法是构造第二个矩对象并指定日期格式。

var endDate = moment("27/09/2019", "DD/MM/YYYY");
Run Code Online (Sandbox Code Playgroud)