First convert the startDate
and endDate
to javascript Date
. Then, declare a variable i
to store while looping through the date. Also, declare holidayIndex
which stores the current index at which holiday date needs to be checked with the current date.
Inside the loop, convert the date to YYYY-MM-DD
format (original format) to check if the current date (isoDate
) lies between a holiday, i.e., it is not a holiday date. If the holidayIndex is at last index of array, then just check if the current date (isoDate
) is not in the holidays array. If not found, then increment numberOfDays
variable.
Otherwise, a holiday date is found, hence no need to increment numberOfDays
. Just increment holidayIndex
to be ready to match the upcoming dates for next holiday date.
Here is the solution:
let numberOfdays = 0;
const startDate = '2022-04-04'; //yy-mm-dd format
const endDate = '2022-04-08';
// Below variable come from db and vary according the start and endate
// eg:- 2022-12-25 will be holiday if we select start and end in december
const holidays = ['2022-04-05', '2022-04-07'];
let holidayIndex = 0;
const start = new Date(startDate);
const end = new Date(endDate);
let i = start;
while (i <= end) {
const isoDate = i.toISOString().split('T')[0];
if (
(holidayIndex < holidays.length - 1 && isoDate < holidays[holidayIndex] && isoDate > holidays[holidayIndex + 1]) ||
formattedDate !== holidays[holidayIndex]
) {
numberOfdays += 1;
} else {
holidayIndex += 1;
}
i.setDate(i.getDate() + 1);
}