[SalesForce] BusinessHours class returns incorrect time difference

I am using business hours class to get the hours, minutes difference between when a lead is assigned to a user and when it is acted upon.

The business hours are 7 AM to 4 PM from Monday to Friday, with Saturday and Sunday off.

Here is the code:

Id businessHoursId = [select Id from BusinessHours where isdefault = true ].id;

DateTime dateTime1 = Datetime.valueOf('2017-08-01 22:16:00'); //last assignment date/time (when a lead is assigned to a sales person)
DateTime dateTime2 = Datetime.valueOf('2017-08-02 09:54:00'); //first activity date/time

Long diff = BusinessHours.diff(businessHoursId, dateTime1, dateTime2);
System.debug('------- diff millseconds: ' + diff);

Decimal hours = (Decimal)diff/1000/60/60;
Decimal mins = (Decimal)diff/1000/60;

System.debug('------- hours: ' + hours);
System.debug('------- minutes: ' + mins);

Now since the lead is acted upon Aug 2, 9:54 AM the difference should be 2:54 (2 hours 54 mins)

However the milliseconds value returned is 10440000

When I convert it to hours I get 2.9, so 2 hours and 90 minutes. I retested it using this tool: http://www.calculateme.com/Time/Milliseconds/ToHours.htm

For minutes it returns 174 minutes.

It does this same thing to other calculations as well where it will add few extra minutes to the difference (by few extra I mean a good amount of 10-15 minutes).

How is this possible? Am I doing anything wrong or does Salesforce adds some extra minutes to the business hours.

Thanks.

Best Answer

The following logic works for me

Long inputMillisecs = BusinessHours.diff(businessHoursId, dateTime1, dateTime2);

Integer total_duration_in_seconds = (inputMillisecs/1000).intValue(); //duration in seconds

Integer hour_result = math.mod(math.floor(total_duration_in_seconds/3600).intValue(),24); //number of hours
Integer minute_result = math.mod(math.floor(total_duration_in_seconds/60).intValue(),60); //number of minutes
Integer second_result = math.mod(math.floor(total_duration_in_seconds/1).intValue(),60); //number of seconds
Related Topic