Robin Walmsley Robin Walmsley - 1 year ago 178
jQuery Question

Javascript/Jquery/Moment.js calculate the number of days between two dates

I've googled loads and read loads, and so far wasted about 3 hours on this. I can't believe its so tough.

I have a Javascript/Jquery app, I have the moment.js plugin installed.
I'm writing a POS application, and I need to calculate the difference in days between two dates, so I can warn the user that a particular returned item might be too old to be returned.

I found this code in JS which looks good and seems to be the popular way to do it, although I just couldn't get it to work

var oneDay = 24*60*60*1000; // hours*minutes*seconds*milliseconds
var firstDate = new Date(2008,01,12);
var secondDate = new Date(2008,01,22);

var diffDays = Math.round(Math.abs((firstDate.getTime() - secondDate.getTime())/(oneDay)));

I also tried this using Moment.js, which again looks really neat

var a = moment([2007, 0, 29]);
var b = moment([2007, 0, 28]);
var x = a.diff(b);

The latter would be my preferred technique. But in my case I get the error "oDate.diff is not a function", here's my code ...

todaysDate = moment(new Date()).format('YYYY, MM, DD');
oDate = moment(result.Order.created).format('YYYY, MM, DD');
var diffDays = oDate.diff(todaysDate, 'days');

I suspect the problem is to do with the format of the oDate variable. But I can't work out why.

EDIT. Incidentally I checked the value of todaysDate and oDate with console.log and they are
todaysDate - 2016, 09, 14
oDate - 2016, 09, 12

Any advice?

Answer Source

Do no use format function before taking the difference. . .once you call format it wont be moment object anymore. format function converts it into a string.

todaysDate = moment(new Date());
oDate = moment(result.Order.created);
var diffDays = oDate.diff(todaysDate, 'days');
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download