2013-01-13 233 views
3

端子输出:为什么moment.js diff方法返回NaN?

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 

代码:

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); 
     } 
+0

您是否使用了最新的moment.js?我使用的是1.7.2,它让我回到'59'。 – robertklep

+0

是的,我正在使用1.7.2。我做了'时刻(expDate._d)',它工作。任何想法为什么? – crzrcn

+0

是expDate一个真正的时刻() - 生成的对象?或者你从JSON反序列化的东西? – robertklep

回答

3

从问题的意见,据我了解,你正试图存储moment实例直接进入MongoDB,然后再检索它。

一个moment没有直接序列化的,所以这总会引起的问题。您应该从现在开始取得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领域中的意见建议。这是内在的时刻,不应该直接使用。这可能不是你所期待的。

+0

谢谢! @ matt-johnson,ISO字符串为我工作。在使用时间戳数据来自JSON /数据库的cordova/phonegap SDK上使用moment()diff()时出现问题。 – sputn1k

+0

@whitedeath - 不确定你的意思,但你确实可以使用其他格式。你只需要[指定格式](http://momentjs.com/docs/#/parsing/string-format/)。 –

+0

不用担心我的评论可能会帮助别人,因为它有助于我的上下文(移动混合 - cordova/phonegap SDK项目 - 其中数据时间戳来自JSON /数据库响应,它在转换时刻返回NaN() - 您的ISO字符串修正了这个,如果这是存储)。 – sputn1k