Skip to content

Instantly share code, notes, and snippets.

@kuovonne
Created March 26, 2020 20:35
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save kuovonne/1a91cd24bb0e4cc9ec8f434adcf2e32b to your computer and use it in GitHub Desktop.
Save kuovonne/1a91cd24bb0e4cc9ec8f434adcf2e32b to your computer and use it in GitHub Desktop.
calculateEndDate script for Airtable scripting block
/*******************************************************************************
Title: calculateEndDate - helper function for Airtable scripting block
Author: Kuovonne Vorderbruggen
Date Created: March 26, 2020
Copyright (c) 2020 by Kuovonne Vorderbruggen
License: MIT License
** Descripton **
This function calculates an end date based on a start date and a duration in days,
not counting weekends as part of the duration.
For example if the start date is a Friday and the duration is 2 days, the end
date would be a Tuesday. If the start date is a Monday and the duration is 5 days,
the end date would be the following Monday.
** Parameters **
startDate: a JavaScript date object (should be a Monday-Friday)
duration: integer (non-negative), duration in days to add
padDurationForWeekends: (optional) boolean, default is true
*******************************************************************************
*/
function calculateEndDate(startDate, duration, padDurationForWeekends = true) {
let endDate = new Date(startDate.toISOString());
endDate.setDate(endDate.getDate() + duration);
if (! padDurationForWeekends) {
return endDate;
}
let startDayOfWeek = startDate.getDay(); // should be 1-5 for Monday-Friday
let completeWeeksInDuration = Math.floor(duration/5); // 5 days in work week
let remainderDaysInDuration = duration % 5; // partial weeks
// calculate if partial weeks require weekend days
let finalWeekendDays = (startDayOfWeek + remainderDaysInDuration >= 6) ? 2 : 0;
let weekendDays = (completeWeeksInDuration * 2) + finalWeekendDays;
endDate.setDate(endDate.getDate() + weekendDays);
return endDate;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment