Last updated on September 18, 2022
DESCRIPTION
There are a number of scenarios where you need the number of days between two dates excluding weekends and holidays. Especially using the business hours and holidays defined in your Salesforce instance.
For example, you want to validate that the duration of the project/task start date and end date must be less than X number of days. Or you want to report on the number of working days the case is closed.
SOLUTION
Step 1:
Define Business hours
Go to Setup > Company Settings > Business Hours
Step 2:
Define Holidays and add business hours to the holidays.
Go to Setup > Company Settings > Holidays
Now use the following apex function to find the number of days excluding holidays between two dates.
public decimal FindNumberOfDays(datetime startDate, datetime EndDate){
//datetime StartDate = system.Now();
//datetime EndDate = system.now().addDays(30);
//if the you have date instead of datetime, then convert a date to datetime
//DateTime DT = DateTime.newInstance(StartDate.year(), StartDate.month(), StartDate.day());
list<BusinessHours> BH = new list<BusinessHours>([SELECT Id, Name, isActive from BusinessHours WHERE isActive = true limit 1]);
decimal NumberOfDays = ((BusinessHours.diff(BH[0].Id, StartDate, enddate) / 3600000) / 24);
system.debug('Result:'+NumberOfDays);
return NumberOfDays;
}
If you want to retrieve the number of business hours between two date times. Then use the following function to find the number of hours.
public decimal FindNumberOfHours(datetime startDate, datetime EndDate){
//if the you have date instead of datetime, then convert a date to datetime
//DateTime DT = DateTime.newInstance(StartDate.year(), StartDate.month(), StartDate.day());
list<BusinessHours> BH = new list<BusinessHours>([SELECT Id, Name, isActive from BusinessHours WHERE isActive = true limit 1]);
decimal NumberOfHours = ((BusinessHours.diff(BH[0].Id, StartDate, enddate) / 3600000));
system.debug('Result:'+NumberOfHours);
return NumberOfHours;
}