davids
davids

Reputation: 5597

Apps Script function to check if certain number of workdays has passed

I have the following script to check if the required number of days has passed since an email was sent:

function test(){
  var ready = readyToSend('01/19/2017 08:00','2d');
}
function readyToSend(lastDate,days){
  var minTimeAgo = new Date();
  minTimeAgo.setTime(subtract(minTimeAgo, days));
  var earliestDate = Utilities.formatDate(minTimeAgo, "GMT-7", "MM/dd/yyyy HH:mm");
  if(earliestDate > lastDate){
    return true;
  }
  return false;
}

This works well for checking if the number of days has passed, but I need to know if the required number of weekdays has passed. So, if lastDate is a Thursday and days is 2, the function shouldn't return true until Tuesday. Right now, it returns true on Monday because 2 days have passed.

How do I ignore weekends in the check for the number of lapsed days?

Upvotes: 1

Views: 456

Answers (1)

user2639740
user2639740

Reputation: 1215

You can try this:

function test(){
  var ready = readyToSend('01/19/2017 08:00','2');
}
function readyToSend(lastDate,days){
  var minTimeAgo = new Date(new Date()-days*24*60*60*1000); // calculate the latest datetime required to meet the delay
  lastDate = new Date(lastDate); // convert lastDate to a Date
  var newDow = lastDate.getDay()*1 + days*1; // calculate the day of the week the new date should be
  if(newDow > 5){ //verify that the lastDate + days does not cross a weekend
    minTimeAgo = new Date(minTimeAgo - 2*24*3600*1000); // if so, subtract another 2 days from the latest acceptible datetime
  }
  if(minTimeAgo > lastDate){
    return true;
  }
  return false;
}

It doesn't work if you need to check beyond a few days into the past (up to one work week).

Upvotes: 1

Related Questions