[SalesForce] Calculation of business hours between two date time fields

Id businessHoursId = [select Id from BusinessHours where isdefault = true ].id;
DateTime dateTime1 = Datetime.valueOf('2015-07-10 12:00:00');
DateTime dateTime2 = Datetime.valueOf('2015-07-13 12:00:00');
Long hours = Math.abs(BusinessHours.diff(businessHoursId,dateTime1,dateTime2)/1000/60/60);
Decimal days = hours / 24.0;

Above code gives 72 hours, but it should be 27 working hours. How can I modify this code to work as expected?

Best Answer

You most likely (from your comment) have not set up the business hours so they are all set to the default of 24 Hours a day 7 days a week.

A quick google search for "Salesforce set up business hours" yielded this gem:

https://help.salesforce.com/articleView?id=customize_supporthours.htm&type=0

To set business hours:

  1. From Setup, enter Business Hours in the Quick Find box, then select Business Hours.
  2. Click New Business Hours.
  3. Type a name for the business hours.
  4. We recommend using a name that will remind users of a location or time zone when they view business hours on a case, entitlement process, or milestone. For example, if your business hours are for a support center in San Francisco, you could use the name San Francisco Business Hours.
  5. Click Active to allow users to associate the business hours with cases, escalation rules, milestones, and entitlement processes. Optionally, click Use these business hours as the default to set the business hours as the default business hours on all new cases. Default business hours on cases can be updated with business hours on escalation rules if the cases match escalation rule criteria and the rule is set to override business hours.
  6. Choose a time zone to associate with the business hours in the Time Zone drop-down list.
  7. Set your business hours for each day of the week.
    • If your support team is available during the entire day every day of the week, select the 24 hours checkbox.
    • Choose the start and end times for the business hours. If the time you want isn’t available, click the field and type it in.
    • Leave the business hours start and end times blank and the 24 hours checkbox deselected to indicate that the support team is not available at all that day.
  8. Click Save.
Related Topic