ship
SalesForce Simplified

Your Go-To Resource for Streamlined Solutions and Expert Guidance

mountains
Empower Your Business
Dive deep into the world of CRM excellence, where innovation meets practicality, and transform your Salesforce experience with Forceshark's comprehensive resources

How to Implement Business Hours Calculation in Apex Code

The BusinessHours class in Apex is a powerful tool provided by Salesforce for calculating business hours. It allows developers to determine working hours, holidays, and other parameters crucial for various business processes. With this class, you can accurately calculate response times, escalation rules, and service level agreements within your Salesforce org.

Creating Business Hours

Creating custom business hours in Salesforce is a straightforward process. Follow these steps to set up your own business hours:

  1. Navigate to Setup in your Salesforce org.
  2. In the Quick Find box, type "Business Hours" and select the appropriate option.
  3. Click on "New Business Hours" and provide a name and description for your business hours.
  4. Specify the working hours for each day of the week, along with any holidays or exceptions.
  5. Save your changes.

During this process, you can customize various parameters such as the start and end times for each day, time zone, and whether or not to include holidays in your calculations.

Configure Holidays

Include holidays by adding them to the holiday list associated with your business hours.

  1. In the Business Hours detail page, scroll down to the "Holiday List" related list.
  2. Click on "New Holiday" to add a new holiday to the list.
  3. Enter the holiday name, date, and any additional information.
  4. Save the holiday.

During the creation process, consider the various parameters available, such as date, time, and recurrence, to tailor the setup according to your organization's requirements.


How to Calculate the Next Business Day in Salesforce Apex

Imagine a scenario where a customer support team in a company has a service level agreement (SLA) to respond to customer inquiries within a certain number of business days. To ensure compliance with this SLA, the team needs a mechanism to calculate the deadline for responding to a customer query, excluding weekends and holidays.

public with sharing class FSRK_BusinessDayCalculator {
    // Method to calculate the next business day
    public static Datetime calculateNextBusinessDay(Datetime currentDateTime, Integer businessDaysToAdd) {
        BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = TRUE];
        return BusinessHours.nextStartDate(bh.Id, currentDateTime.addDays(businessDaysToAdd));
    }
}

In this context, the FSRK_BusinessDayCalculator class can be utilized. When a new customer inquiry is received, the system can invoke the calculateNextBusinessDay method, passing the current date and time along with the desired business days for response. The returned result would represent the deadline for responding to the customer, considering the organization's business hours and any designated holidays.

How to Extend a DateTime by Business Hours Using Apex

This method allows you to add a specified number of business hours to a given datetime. Let's say you have a support case that needs to be resolved within 24 business hours. 

You can use the add method to calculate the deadline for resolving the case based on the current datetime and the business hours of your organization.

public with sharing class FSRK_BusinessHoursAddExample {
    public static Datetime calculateDeadline(Datetime startDate, Integer hoursToAdd) {
        BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = TRUE];
        return BusinessHours.add(bh.Id, startDate, hoursToAdd);
    }
}    

How to Calculate Business Hour Duration Between Two DateTime Values

The diff method calculates the difference in business hours between two datetime values. Suppose you need to calculate the turnaround time for processing orders. You can use the diff method to determine how many business hours elapsed between the creation and completion of an order.

public with sharing class FSRK_BusinessHoursDiffExample {
    public static Decimal calculateTurnaroundTime(Datetime startDate, Datetime endDate) {
        BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = TRUE];
        return BusinessHours.diff(bh.Id, startDate, endDate);
    }
}

How to Check if a Given DateTime is Within Operational Hours

This method checks if a given datetime falls within business hours. For instance, you might want to validate if a scheduled maintenance window overlaps with business hours to avoid disruption to users. Use the isWithin method to determine if the maintenance window falls within acceptable hours.

public with sharing class FSRK_BusinessHoursIsWithinExample {
    public static Boolean isMaintenanceWindowValid(Datetime maintenanceStart, Datetime maintenanceEnd) {
        BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault = TRUE];
        return !BusinessHours.isWithin(bh.Id, maintenanceStart) && !BusinessHours.isWithin(bh.Id, maintenanceEnd);
    }
}

Conclusion

Implementing business hours calculation in Apex using the BusinessHours class is essential for managing various time-sensitive processes within Salesforce. By creating custom business hours and leveraging the provided methods, developers can ensure accurate and efficient handling of tasks based on organizational working hours and requirements.