0

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?

4 Answers 4

4

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;
Sign up to request clarification or add additional context in comments.

3 Comments

Thanks this worked. Do you know if I can do the math at presentation layer in AngularJS if I have {{dateone}} and {{datetwo}}
@JotiBasi Yes, you should be able to do the calculation in HTML {{(datetwo - dateone) / 1000 / 60 / 60 / 24}} this should work.
@Titus I can not do arithmetic operation directly to your dateone & datetwo objects. var timeDiff = Math.abs(datetwo.getTime() - dateone.getTime()); var diffDays = Math.ceil(timeDiff / (1000 * 3600 * 24)); console.log("<<<<<<< diffDays >>>>>>>>.", diffDays); This works for me. I think this will help.
2

You can easily do with moment.js

var a = moment('2016-08-21T07:00:00.000Z');
var b = moment('2016-08-28T07:00:00.000Z'); 
var days = b.diff(a, 'days');

JsFiddle

Comments

1
let invitedDate = '2019-11-27T05:19:23.32';
let deference = new Date().getTime() - new Date(invitedDate).getTime();
let days = Math.round(Math.abs(deference / (1000 * 60 * 60 * 24)));

if you need to get the deference between 2 different days what can do is, get using Date.getTime() and the invited Date example as above calculate the Days

1 Comment

answers without explanation are marked as low quality... can you add some explanation
0

As well as what Titus said about turning them into Dates rather than Strings, try something like this:

var oneDay = 24*60*60*1000; // Calculates milliseconds in a day
var diffDays = Math.abs((dateone.getTime() - datetwo.getTime())/(oneDay));

I don't know what you expected Math.round() to do for you, but I don't see that helping much. Math.abs() ensures that the difference is positive, while subtracting the two getTime() functions gets the difference in milliseconds.

Hope this helps.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.