JavaScript: How to calculate the number of days between two dates

The following function takes in two dates and returns the number of days between them:

// Calculate the difference of two dates in total days
function diffDays(d1, d2) {
  let numDays = 0;
  let tv1 = d1.getTime();  // msec since 1970
  let tv2 = d2.getTime();

  numDays = (tv2 - tv1) / 1000 / 86400;
  numDays = Math.round(numDays - 0.5);
  return numDays;
}

This is very handy if you want to find the number of days that have elapsed since some day in the past, or if you want to calculate the number of days something is over due.  First you set up the two dates that you are interested in. In this case, the second day is today.

let startDate = new Date('2017-01-20 11:00:00');  // 2000-01-01
let endDate =   new Date();                       // Today

Then you call the function like so:

let elapsedDays= diffDays(startDate, endDate);
console.log(elapsedDays);

which yields 543.

This function uses the getTime() method, which returns the numeric value associated with a UTC date. Getting the date as a numeric value is useful for these types of calculations, such as getting the number of days between two dates. This same method can be used to get the number of weeks, months, hours, seconds, etc..

Here are some comments detailing how it works:

// This is the number of miliseconds since Jan 1, 1970, 00:00:00.000 GMT
numDays = (tv2 - tv1);

// = 46945658190

// Divide by 1000 to get seconds from miliseconds
numDays = (tv2 - tv1) / 1000;

// = 46945658.19


// Divide by 86400 (the number of seconds in a day) to get days
numDays = (tv2 - tv1) / 1000 / 86400;

// = 543.3525842824074

// Round the result
numDays = Math.round(numDays - 0.5);

// = 543

For more information about the getTime() method, see:
https://developer.mozilla.org/en-US/docs/Web/JavaScript/Reference/Global_Objects/Date/getTime
https://www.w3schools.com/jsref/jsref_gettime.asp