How to get total days between two dates in JavaScript?

It is very handy to know the total number of days between two dates. Using JavaScript we can do it in real quick. JavaScript has extensive support of manupulating and customizing dates. Lets consider a date range and try to construct a function to find number of days between those two dates. Following is the function:

Function definition

function getDaysdiffBetweenDates(startDate, endDate){
    var onedaySecond = 1000 * 3600 * 24;
    var timeDiff = Math.abs(endDate.getTime() - startDate.getTime());
    var diffDays = Math.floor(timeDiff / onedaySecond);
    return diffDays;
 }

Function calling

 var startFrom = "12/15/2018 00:00:00";
 var startDate = new Date(startFrom);
 var endDate = new Date();
 var daysdiff = getDaysdiffBetweenDates(startDate, endDate);
 cosnole.log(daysdiff);

How the above function work?

We simply need two JavaScript date objects to find the difference. In this case we set a static date as start date and choose the current date as end date. Now inside the diff function we simply used the timestamp of start and end dates to get the differences. we got the differences in seconds. We calculated number of seconds in a day. Finally we divide the timedifferences with the seconds per day. That gives us the correct number of days between two dates.

Share