1

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.

0

You should create a Utility class like this

public with sharing class BusinessHoursServices
{
    //retrieves & assign the Organization level Business Hours to defaultBH 
    @testVisible static BusinessHours defaultBH
    {
        get
        {
            if (defaultBH == null)
                defaultBH = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
            return defaultBH;
        }
        private set;
    }

    public static Boolean isWithin()
    {
        return isWithin(Datetime.now());
    }

    public static Boolean isWithin(Datetime input)
    {        
        return BusinessHours.isWithin(defaultBH.Id, input);
    }

    public static  Datetime nextStartDate()
    {
        return nextStartDate(Datetime.now());
    }

    public static Datetime nextStartDate(Datetime input)
    {
        return BusinessHours.nextStartDate(defaultBH.Id, input);
    }

    public static Datetime getSLATimeByBusinessHour (DateTime input, Integer SLAhours)
    {        
        return BusinessHours.add(defaultBH.Id,input, SLAhours* 60 * 60 * 1000L);
    }

}

and call getSLATimeByBusinessHour with appropriate parameters.

For more information refer my blog post Example of BusinessHours calculation

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.