+ Start a Discussion
Oliver Freeman 29Oliver Freeman 29 

Issue using BusinessHours.diff


I'm currently working on implementing a time off booking system for our internal Salesforce org.
We have two different Business Hours records which reflect our two different working hours for employees - M2F - Monday to Friday, and M2T - Monday to Thursday.
We don't take holidays by the hour, we take them either in half days, or full days, so those business hours records are used purely for the holiday booking system, and to make things easier, are set to 24Hrs for each day worked in that particular record.

My idea was to use an APEX trigger to calculate the difference in business hours based on the particular users specified (at the User object level) business hours record - this works fine, however, if I try to create a 'Time Off' record that is 4 days in duration, the returned 'Number of Days' from my BusinessHours.diff calculation(s) is 3.96 days, not 4.

See my method here:
public static void calculateDays(List<Time_Off__c> timeOff){
        List<Time_Off__c> tu = new List<Time_Off__c>();
        for(Time_Off__c t:timeOff){
            Time_Off__c to = new Time_Off__c(Id=t.Id);
            String userBh = [SELECT Id, Business_Hours__c FROM User WHERE Id = :t.User__c LIMIT 1].Business_Hours__c;
            Id bhId = [SELECT Id, Name FROM BusinessHours WHERE Name =: userBh].Id;
            Long diffMs = BusinessHours.diff(bhId, t.Start_Date__c, t.End_Date__c);
            Double hours = diffMs/3600000;
            Double days = hours/24;
            to.Number_of_Days__c = days;
        update tu;

Any help would be massively appreciated :)


Lokeswara ReddyLokeswara Reddy
Hi Oliver,
Were you able to solve this? BusinessHours.diff returning time difference only for the Business Hour record which is marked as default, this returns zero when I pass other BusinessHour record.