Check date time occurs within Business Hours Salesforce Apex

Check date time occurs within Business Hours Salesforce Apex

In Salesforce Apex, we can make use of BusinessHours.isWithin() method to check whether the date time is within the business hours or not.

Please check the following apex code for reference.

Sample Apex Code:

// Fetching the Business Hours
BusinessHours objBH = [
    SELECT Id, TimeZoneSidKey 
    FROM BusinessHours 
    WHERE IsDefault = true
];

// Getting Time Zone
Timezone tz = Timezone.getTimeZone( objBH.TimeZoneSidKey );
System.debug( tz );

// Current Date Time in GMT
Datetime nowDT = Datetime.now();

// Finding the Offset between GMT and Business Hours Time Zone
Integer intOffset = UserInfo.getTimezone().getOffset( nowDT );

// Getting the Business Hours Time Zone Date Time
Datetime objBHDT = nowDT.addSeconds( intOffset/1000 );
System.debug(
    'Business Hours Date Time is ' + 
    objBHDT
);

// Checking whether it is withing Business Hours
Boolean isWithinBH = BusinessHours.isWithin(
    objBH.Id, 
    objBHDT
);
System.debug(
    'Is it within Business Hours?: ' + 
    isWithinBH
);

Leave a Reply