Joti Basi Joti Basi - 1 year ago 99
AngularJS Question

AngularJS - Javascript number of days between two dates

I have two dates that I get in the following format - that are returned from a web service:

var dateone = "2016-08-21T07:00:00.000Z";
var datetwo = "2016-08-28T07:00:00.000Z";

var datediff = datetwo - dateone;

var numdays = Math.round(datediff);
console.log("Number of Days is " + numdays);

I get NaN. What am I missing here?

Answer Source

Your dateone and datetwo variables are Strings not Dates. Try this:

var dateone = new Date("2016-08-21T07:00:00.000Z"); 
var datetwo = new Date("2016-08-28T07:00:00.000Z");

Also, substracting 2 Dates objects will give you the difference between them in milliseconds, if you want to determine the number of days, you can do something like this:

var dayDif = (datetwo - dateone)  / 1000 / 60 / 60 / 24;
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download