JavaScript: calculate the difference in days between two dates

JavaScript: calculate the difference in days between two dates

In JavaScript we can get the difference in days between two dates.

In JavaScript we can get the difference in days between two dates.

The solution is as follows:


'use strict';

const differenceBetweenDates = (date1, date2) => {
     const tsDifference = date1.getTime() - date2.getTime();
     return Math.floor(tsDifference / (1000 * 60 * 60 * 24));
};

The arguments date1 and date2 represent two objects of type Date which represent the reference dates with which you want to calculate the difference.

date1.getTime() and date2.getTime() are called to get the millisecond timestamps of the two dates. Timestamps represent the number of milliseconds between January 1, 1970 and midnight UTC on the specified date.

The difference between the two timestamps is calculated by subtracting the timestamp of date2 from that of date1. This returns the difference in milliseconds between the two dates.

The difference in milliseconds is then divided by (1000 * 60 * 60 * 24), which equals 86400000 milliseconds (the number of milliseconds in a day) to get the number of days.

Math.floor() is used to round the result down to the nearest integer. This is useful because the difference in days may have a decimal part due to time zone differences or summer times. Finally, the result is returned as the output of the function.