Friday, 3 July 2015

Calculate number of Business Days between two dates except holidays and weekends in Salesforce

          The below code will find the number of business days between two days. Change the below code according to your requirement.

         By default, I have assigned Saturday and Sunday as default weekend. Change this code according to your requirement.

  1. public class BusinessDayCalculation
  2. {
  3.     public static Integer calculateWorkingDays(Date startDate, Date endDate)
  4.     {        
  5.         Set<Date> holidaysSet = new Set<Date>();
  6.        
  7.         for(Holiday currHoliday : [Select ActivityDate from holiday])
  8.         {
  9.             holidaysSet.add(currHoliday.ActivityDate);
  10.         }
  11.        
  12.         Integer workingDays = 0;
  13.        
  14.         for(integer i=0; i <= startDate.daysBetween(endDate); i++)
  15.         {
  16.             Date dt = startDate + i;
  17.             DateTime currDate = DateTime.newInstance(dt.year(), dt.month(), dt.day());
  18.             String todayDay = currDate.format('EEEE');
  19.             if(todayDay != 'Saturday' && todayDay !='Sunday' && (!holidaysSet.contains(dt)))
  20.             {
  21.                 workingDays = workingDays + 1;
  22.             }
  23.         }
  24.        
  25.         System.debug('--Working days'+workingDays);
  26.         return workingDays;
  27.     }
  28. }



2 comments:

  1. how to apply this class into salesforce object??

    ReplyDelete
  2. Can you write a logic for count half day am and half day pm checkbox value in this code ???

    ReplyDelete

Activities: Assign Tasks to a Queue Salesforce Lightning

Salesforce announced to assign Tasks to a Queue beginning from Spring'20 release. How does it work? In Setup, enter Queues in th...