If you search online, you'll find any number of sources to provide the formula, with varying degrees of clarity on the explanation. A recent search shows that almost all of them are using an old approach to finding the day of the week that was in common usage before Salesforce existed. It uses the MOD() function from math, and depends on you knowing that January 7, 1900 was a Sunday.
If you take any date, your birthday for example, and subtract the date for January 7, 1900, you get X days. Divide X by 7 and ignore that result, but pay attention to the remainder. Since you divided by 7, you won't have a remainder larger than 6. You can determine the day of the week for your birthday:
- 0 = Sunday
- 1 = Monday
- 2 = Tuesday
- 3 = Wednesday
- 4 = Thursday
- 5 = Friday
- 6 = Saturday
Most of the formulas that I've seen referenced, including in Salesforce's own docs, end up as some variation of this one, which adds 3 business days. If you want to add some other number of days, you have to understand the formula well enough to add or delete lines.
I found this other formula in a few places, which leaves the number of days to add as a variable in the formula. In this case, we use the FLOOR() and CEILING() functions to dynamically determine whether weekend days are involved.
I was really impressed to see another approach from Lightning Champion John Knight on the Cloud Trailz blog. John takes advantage of a built-in function called WEEKDAY() that returns the day of the week.
If you've been using the MOD() function, you're probably used to thinking of Sunday = 0, but this one starts Sunday = 1, so don't let that trip you up. Using this function, look how simple John's formulas are:
Add 2 Weekdays:
Short and clean! Check out John's full post for other examples. If you want to add the flexibility for any number of days, while using the WEEKDAY() function, it looks like this:
I think that one gets my vote for cleanest and most flexible. Now, we just need somebody to figure out how to handle holidays!
UPDATE: Somebody figured out how to handle holidays!
Less than a day after my post, Jason Hoult pointed me to a blog by Cheney Shreve. In her remarkable post Traversing the declarative and programmatic divide: The same task with 3 different Salesforce Tools, Cheney shows how to use the Business Hours setting, in combination with Workflow Rules, Processes, and Invocable Apex, to create Holiday settings and add DateTime into the equation. I recommend reading it.e
Post a Comment