const today = new Date();
var date2 = new Date("10/29/2021");
var Difference_In_Time = date2.getTime() - today.getTime();
var Difference_In_Days = Difference_In_Time / (1000 * 3600 * 24);
document.write(
"Total number of days between dates <br>" +
today +
"<br> and <br>" +
date2 +
" is: <br> " +
Difference_In_Days
);
Asked
Active
Viewed 283 times
0

R. Oosterholt
- 7,720
- 2
- 53
- 77

Reda Mohammed
- 13
- 1
-
1please explain the problem and your expectation about the above code snippet. thanks – nima Sep 29 '21 at 13:51
-
Please explain your problem more clearly. It is quite unclear question – Shubham Pratik Sep 29 '21 at 13:55
-
Regarding `new Date("10/29/2021")`, see [*Why does Date.parse give incorrect results?*](https://stackoverflow.com/questions/2587345/why-does-date-parse-give-incorrect-results) – RobG Sep 30 '21 at 00:09
1 Answers
-1
First explain what is the issue.
But if you just want one of the correct way of getting date differences. You should look below code.
And don't subtract bigger date from smaller one. If you want to do like that you must get its absolute value. You should do like below code.
const date1 = new Date('9/20/2021');
const date2 = new Date();
const diffTimeInMilliseconds = Math.abs(date2 - date1); // this gives time difference in milliseconds
const diffDays = Math.floor(diffTimeInMilliseconds / (1000 * 60 * 60 * 24)) // 1 second = 1000 ms, 1 minute = 60 s, 1 hour = 60 m, 1 day = 24 h;
console.log(diffTimeInMilliseconds + " milliseconds");
console.log(diffDays + " days");

Nbody
- 1,168
- 7
- 33
-
Code only answers aren't helpful. A good answer should explain why the OP has their issue and how your answer fixes it. It's not clear from the OP what the issue is, and there are already many questions and answers regarding getting the difference between dates in days, hours, whatever. – RobG Sep 30 '21 at 00:11