Issue
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
);
Solution
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");
Answered By - n-ata
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.