I am working on a method that adds business days using the BusinessHours class.
Here is the method I'm working on:
public static Date addBusinessDays(Date d, integer dayDifference, Id businessHoursId)
{
if(d != null) {
if(dayDifference > 0)
{
integer counter = dayDifference;
for(integer i = 1; i <= counter; i++) {
if(!BusinessHours.isWithin(businessHoursId, (Datetime)d.addDays(i)))
{
counter++;
}
}
return d.addDays(counter);
}
else
{
integer counter = dayDifference;
if(d != null) {
for(integer i = -1; i >= counter; i--)
{
if(!BusinessHours.isWithin(businessHoursId, (Datetime)d.addDays(i))) {
counter--;
}
}
return d.addDays(counter);
}
}
}
return null;
}
I'm using the BusinessHours isWithin
method inside the loop and that is causing a CPU limit exception. I'm trying to figure out if there is a way to re-factor the method and move the isWithin
method outside of the loop or some way to re-factor to avoid the CPU limit exception.