Introduction
In this lab, we will explore a JavaScript program that counts the number of weekdays between two given dates. The program uses an array and the reduce method to iterate over the given range of dates, checking if each date is a weekday and incrementing the count accordingly. However, it should be noted that this program does not take official holidays into account.
Count Weekdays Between Two Dates
To count the weekdays between two dates, follow these steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use
Array.from()to create an array with a length equal to the number of days betweenstartDateandendDate. - Use
Array.prototype.reduce()to iterate over the array, checking if each date is a weekday and incrementingcount. - Update
startDatewith the next day each loop usingDate.prototype.getDate()andDate.prototype.setDate()to advance it by one day. - Please note that this function does not take official holidays into account.
Here's the code to implement this:
const countWeekDaysBetween = (startDate, endDate) =>
Array.from({ length: (endDate - startDate) / (1000 * 3600 * 24) }).reduce(
(count) => {
if (startDate.getDay() % 6 !== 0) count++;
startDate = new Date(startDate.setDate(startDate.getDate() + 1));
return count;
},
0
);
You can use the following code to test the function:
countWeekDaysBetween(new Date("Oct 05, 2020"), new Date("Oct 06, 2020")); // 1
countWeekDaysBetween(new Date("Oct 05, 2020"), new Date("Oct 14, 2020")); // 7
Summary
Congratulations! You have completed the Count Weekdays Between Two Dates lab. You can practice more labs in LabEx to improve your skills.