Hi,
Dealing with date and time operations in JavaScript is always a pleasure . I recently needed to add some workdays to dates in Airtable script and I thought it might be helpful to share it here (even in case I need to find it again).
Adding days (regular days) to a date
function addDaysRegular(date, days) {
let result = new Date(date);
result.setDate(result.getDate() + days);
return result;
}
Adding workdays to a date
function addWorkDays(date, workdays) {
let endDate = new Date(date);
let workdaysRemaining = workdays
while (workdaysRemaining > 0){
endDate = addDaysRegular(endDate,1)
if (endDate.getDay() !== 0 && endDate.getDay() !== 6)
workdaysRemaining--;
}
return endDate;
Note that above function:
- is reusing the first function
- could be customized for workdays in Middle East by changing the if statement to
if (endDate.getDay() !== 5 && endDate.getDay() !== 6)
Adding workdays to a date excluding holidays
Holidays get tricky and irregular(especially US ones), so I went just for declarative way of describing them, so that pattern is fairly easy to adjust by non-coders . If someone has smarter way of doing this, please let me know.
const holidays = {
// "day,month": "holiday name for reference"
"1,1": "New Year's Day",
"19,2": "test holiday",
"20,2": "test holiday",
"21,2": "test holiday",
"8,31": "Summer Bank Holiday",
"12,25": "Christmas Day",
"12,26": "Boxing Day"
};
And for the main function we reuse previous one with small modification:
function addWorkDays(date, workdays) {
let endDate = new Date(date);
let workdaysRemaining = workdays
while (workdaysRemaining > 0){
endDate = addDaysRegular(endDate,1)
if (endDate.getDay() !== 0
&& endDate.getDay() !== 6
&& !holidays[`${endDate.getDate()},${endDate.getMonth()+1}`])
workdaysRemaining--;
}
return endDate;
}
Here is a link to a scripting block implementing the above functions:
I hope that saves someone some research in the future.