Salesforce BusinessHours Calculation

//Get the default business hours
Id businessHourId = [SELECT Id FROM BusinessHours WHERE IsDefault = true].Id;

//Get the next date when business hours are open. If the specified target date falls within business hours, this target date is returned.
Datetime targetDate = system.today();
Datetime nextDate = BusinessHours.nextStartDate(businessHourId, targetDate);

//Check target date occurs within business hours. Holidays are included in the calculation.
Datetime targetDate = system.today();
Boolean isWithinBusinessHour = BusinessHours.isWithin(businessHourId, targetDate);

//Get the difference between a start and end Datetime based on a specific set of business hours in milliseconds.
Datetime startDT = system.today();
Datetime endDT = DateTime.Now().AddDays(2);
Long difference = BusinessHours.diff(businessHourId, startDT, endDT);
Double hours = difference/3600000;

//Adds an interval of time from a start Datetime traversing business hours only. Returns the result Datetime in the local time zone.
Datetime startDT = system.today();
Long intervalMilliseconds = 50000;
Datetime targetDT = BusinessHours.add(businessHourId, startDT, intervalMilliseconds);

1 Star2 Stars3 Stars4 Stars5 Stars (3 votes, average: 5.00 out of 5)
Loading...

About Biswajeet

Biswajeet is my Name, Success is my Aim and Challenge is my Game. Risk & Riding is my Passion and Hard Work is my Occupation. Love is my Friend, Perfection is my Habit and Smartness is my Style. Smiling is my Hobby, Politeness is my Policy and Confidence is my Power.

  • sweety kumari

    Thanks for this post. I tried the same code in my org but it is giving error that illegal assignment from Long to DateTime.

    Note: BusinessHours.diff(businessHourId, startDT, endDT) :- (Illegal assignment from Long to Datetime) , this will always return Long value. So we need to convert this to Date time.

    Thanks,
    SWeety

    • Send me the code

      • sweety kumari

        same code that you posted.

        //Get the difference between a start and end Datetime based on a specific set of business hours in milliseconds.
        Datetime startDT = system.today();
        Datetime endDT = DateTime.Now().AddDays(2);
        Datetime difference = BusinessHours.diff(businessHourId, startDT, endDT);
        Double hours = difference/3600000;

        • Thanks for your information.
          Yes it was an error which I have fixed.
          Please check and let me know.

          • sweety kumari

            yeah, it’s working fine now.