Salesforce: Adding specific business days to date using BusinessHours class

Businesshours is a system class provided by Salesforce for performing various operations on the datetime values. It provides methods for checking if date falls in business hours, whats the diff between two dates in business.

In-built method does allow adding the specific days to the datetime value but there is a catch, it needs to be in the Long format. More information could be found here.

add(businessHoursId, startDate, intervalMilliseconds)

What exactly this method does?

Method has been specifically designed to add the number of hours in the milliseconds format. And addition is done with respect to business hours. Lets consider you want to add 1 day in the Date December 18th, 10 AM. And business hours are set for 8 AM to 8 PM for all days.

Long interval = 24 * 60 * 60 * 1000;
                 h   m    s    ms
Datetime dt = DateTime.newInstance(2017, 12, 18, 10,0,0);
System.debug('Date :' + dt.format());
Long interval = (24 * 60 * 60 * 1000);
Datetime newdt = BusinessHours.add(bh.Id, dt, interval);
System.debug('After adding 1 day :' + newdt.format());

22:12:52:003 USER_DEBUG [3]|DEBUG|Date :12/18/2017 10:00 AM
22:12:52:004 USER_DEBUG [6]|DEBUG|After adding 1 day :12/20/2017 10:00 AM

This calculation added complete 2 days as business hours are set 12 hours a day.

Alternative for avoiding such hour based calculation could be going in a iterative way.

public static Datetime addBusinessDays(Datetime startDate, Integer numberOfDays, id busniesshourId)
    Integer count = 0;
    while (count < days)
        startDate = startDate.addDays(1);
        if (BusinessHours.isWithin(businesshourId, startDate)) 
    return startDate;

This will also ensure that the initial time is preserved.

Leave a Reply

%d bloggers like this: