How can I calculate business hours between two dates? For example, we have two dates; 01/01/2010 15:00 and 04/01/2010 12:00 And we have working hours 09:00 to 17:00 in weekdays How can I calculate working hours in Salesforce formula field


You can't do it with a formula field.

You can do it with Apex (and a trigger) to calculate the business hours between two fields based on a Business Hours record.

The example on the formulas page won't be much help, as it's not dynamic to account for holidays like are available when using the Business Hours object.


Rather than complicated formula, write a class like below and call getBusinessHourTimeDifference with correct parameters.

public with sharing class BusinessHoursServices
    @testVisible static BusinessHours defaultBH
            if (defaultBH == null)
                defaultBH = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
            return defaultBH;
        private set;

    * getBusinessHourTimeDifference
    * returns business hours difference in milliseconds based on two datetime. 
    * @param businessHoursId - BusinessHour Id
    * @param startDate - start date time
    * @param endDate - end date time
    * @return Long
    public static Long getBusinessHourTimeDifference(Datetime startDate, Datetime endDate)
        return BusinessHours.diff(defaultBH.Id, startDate, endDate);

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