Introduction
In this lab, we will explore a JavaScript function that helps calculate the date after adding a given number of business days. The function uses array manipulation and date iteration to increment the start date while taking weekends into account. This lab will help you understand how to manipulate dates in JavaScript and apply business logic to date calculations.
Function to Add Business Days to a Given Date
To calculate a future date by adding a given number of business days, you can use the addWeekDays function. Here are the steps:
- Open the Terminal/SSH and type
nodeto start practicing coding. - Use the
addWeekDaysfunction that takes two arguments:startDateandcount. startDateis the date from which you want to start adding business days.countis the number of business days you want to add to the start date.- The function constructs an array using
Array.from()method and sets the length equal to thecountof business days to be added. Array.prototype.reduce()method is used to iterate over the array, starting fromstartDate, and incrementing it usingDate.prototype.getDate()andDate.prototype.setDate().- The function checks whether the current
dateis on a weekend or not. - If the current
dateis on a weekend, the function updates it again by adding either one day or two days to make it a weekday. - The function does not take official holidays into account.
const addWeekDays = (startDate, count) =>
Array.from({ length: count }).reduce((date) => {
date = new Date(date.setDate(date.getDate() + 1));
if (date.getDay() % 6 === 0)
date = new Date(date.setDate(date.getDate() + (date.getDay() / 6 + 1)));
return date;
}, startDate);
Here are some examples of how you can use the addWeekDays function:
addWeekDays(new Date("Oct 09, 2020"), 5); // 'Oct 16, 2020'
addWeekDays(new Date("Oct 12, 2020"), 5); // 'Oct 19, 2020'
Summary
Congratulations! You have completed the Add Weekdays to Date lab. You can practice more labs in LabEx to improve your skills.