Search code examples
javascriptnode.jsmomentjsjsxiso8601

Moment JS not recognising ISO 8601 date


So I've got two dates I'd like to get the difference of:

console.log(new Date(Date.now()).toISOString()); //2017-07-07T16:55:30.471Z
console.log(asset.past[i].date); //2017-07-06T20:29:00.670Z
var a = moment([new Date(Date.now()).toISOString()]);
console.log(a); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
var b = moment([asset.past[i].date]);
console.log(b); //Moment Date:Sun Jan 01 2017 00:00:00 GMT+0000
console.log(a.diff(b, 'seconds', true)); //0
console.log(a.diff(b, 'days', true)); //0
console.log(a.diff(b, 'months', true)); //0

I've put the out put of the console logs as comments afterwards. I assume it doesn't recognize the date format as ISO 8601 and defaults to Sun Jan 01 2017 00:00:00 GMT+0000. Either way, any idea how to fix it?

Cheers, Ed.


Solution

  • Why are you passing in an array to the moment constructor? What do you want a to actually be, just the current date? If so just do moment(). If you want to pass in a string do it like you correctly did on line 1.

    Here are just the 2 fixes where I removed the square brackets. Again, you can just do moment() to get a moment that points to now.

    // var a = moment(new Date(Date.now()).toISOString());
    var a = moment();
    var b = moment(asset.past[i].date);