Skip to main content
sfadm sfadm (RPA) ha preguntado en #Apex

I need to calculate the out of office hours in apex.

The hours are:

6 pm – 9 am Mon – Fri

and

6 pm on Fri till 9 am on Mon

I've already configured the Business Hours:

Monday09:00to18:00

Tuesday09:00to18:00

Wednesday09:00to18:00

Thursday09:00to18:00

Friday09:00to18:00

Saturday24 Hours

Sunday24 Hours

and activate it in Salesforce.

Please advise how it can be achieved in apex?
3 respuestas
  1. 19 jul 2017, 13:23
    Hi,

    For any Day first thing you can check is If the date is a Business Day of not using below method

    BusinessHours.isWithin(businessHoursId, targetDate)

    businessHoursId will be the calendar Id

    targetDate will be the date for which u are looking to calculate business hours

    Example

    // Get the default business hours

    BusinessHours bh = [SELECT Id FROM BusinessHours WHERE IsDefault=true];

    // Create Datetime on May 28, 2013 at 1:06:08 AM in the local timezone.

    Datetime targetTime = Datetime.newInstance(2013, 5, 28, 1, 6, 8);

    // Find whether the time is within the default business hours

    Boolean isWithin= BusinessHours.isWithin(bh.id, targetTime);

     Using the same developer refrence,

    If it returns true, u can take the tagretDate time and subtract it from 18:00 number of pending hours will give you business hours remaining for that day.

    Does that help?

    Thanks