# Finding Number of Days Between Two Dates JavaScript

We are required to write a JavaScript function that takes in two dates in the 'YYYY-MM-DD' format as the first and second argument respectively. The function should then calculate and return the number of days between the two dates.

For example −

If the input dates are −

const str1 = '2020-05-21';
const str2 = '2020-05-25';

Then the output should be −

const output = 4;

## Example

const str2 = '2020-05-25';
const daysBetweenDates = (str1, str2) => {
const leapYears = (year, month) => {
if (month <= 2){
--year;
};
let floor = Math.floor;
return floor(year / 400) + floor(year / 4) - floor(year / 100);
};
let monthDays = [0, 0, 31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30];
for (let i = 1; i < monthDays.length; ++i){
monthDays[i] += monthDays[i - 1];
};
let days = (year, month, d) => (year * 365) + leapYears(year, month) + monthDays[month] + d; let p = days(...str1.split('-').map(Number));
let q = days(...str2.split('-').map(Number));
return Math.abs(p - q);
};
console.log(daysBetweenDates(str1, str2));

## Output

And the output in the console will be −

4

Updated on: 25-Nov-2020

161 Views

Get certified by completing the course