Tag Archives: BusinessHours

Salesforce BusinessHours Calculation

//Get the default business hours
Id businessHourId = [SELECT Id FROM BusinessHours WHERE IsDefault = true].Id;

//Get the next date when business hours are open. If the specified target date falls within business hours, this target date is returned.
Datetime targetDate = system.today();
Datetime nextDate = BusinessHours.nextStartDate(businessHourId, targetDate);

//Check target date occurs within business hours. Holidays are included in the calculation.
Datetime targetDate = system.today();
Boolean isWithinBusinessHour = BusinessHours.isWithin(businessHourId, targetDate);

//Get the difference between a start and end Datetime based on a specific set of business hours in milliseconds.
Datetime startDT = system.today();
Datetime endDT = DateTime.Now().AddDays(2);
Datetime difference = BusinessHours.diff(businessHourId, startDT, endDT);
Double hours = difference/3600000;

//Adds an interval of time from a start Datetime traversing business hours only. Returns the result Datetime in the local time zone.
Datetime startDT = system.today();
Long intervalMilliseconds = 50000;
Datetime targetDT = BusinessHours.add(businessHourId, startDT, intervalMilliseconds);