Script for offsetting dates by business/working days

Getting notifications or having tasks become due on weekends isn’t very useful. And as far as I can tell there’s no way to do this via a formula so here is a pretty simple script to add working/business days to a date. Meaning:

  • Thursday + 1 business day = Friday
  • Friday + 1 business day = Monday
  • Saturday & Sunday + 1 business day = Monday
  • Monday + 1 business day = Tuesday
function addBizDays(startDate, bizDays) {
    for (let i = 1; i <= bizDays; i++) {
        startDate.setDate(startDate.getDate() + 1);
        if (startDate.getDay() === 6) {
            startDate.setDate(startDate.getDate() + 2);
        }
        else if (startDate.getDay() === 0) {
            startDate.setDate(startDate.getDate() + 1);
        }
    }
    return new Date(startDate);
}

const fibery = context.getService('fibery');
for (const entity of args.currentEntities) {
    // an entity contains all fields apart from collections, to access a field refer to it by its UI name
    const startDate = new Date(entity['Start Date']);
    const businessDays = entity['Add Biz Days'];
    // to update an entity provide an object with the new values
    await fibery.updateEntity(entity.type, entity.id, {
        'Result Date': addBizDays(startDate, businessDays).toISOString().split('T')[0],
    });
}

So in the above example Start Date is a DB date field that is the input date, Add Biz Days is the DB field that holds the number of days to offset the Start Date by, and Result Date is the output date field.

If you want the start date to always be today just do this:

const startDate = new Date();

If you want the offset days to be a fixed value just do something like this:

const businessDays = 2;
6 Likes

This is another good example of why it would be useful to have some sort of Workspace library/module support for scripts.

6 Likes