[SalesForce] Number of holidays between two dates

Any idea of how to calculate the number of holidays between two given dates?

Object: Time_Off__c

Fields: Start_date__c, End_date__c , Included_Holidays__c presenting the number of holidays between Start_date__c and End_date__c

 public static List<Holiday> lstHolidays = new List<Holiday>();
/*************** Holidays days number between Start 'n End date ***********/
public static void MyHolidays(List<Time_Off__c> lstTimeOff){
    try{
    lstTimeOff=[Select Start_date__c, End_date__c,Included_Holidays__c From Time_Off__c];
    lstHolidays = [Select ID,ActivityDate From Holiday ];
    for (Time_Off__c TO: lstTimeOff){
        for(Holiday h: lstHolidays){
        if(h.ActivityDate >= TO.Start_date__c &&    h.ActivityDate<= TO.End_date__c)
        System.debug('###h.ActivityDate'+ h.ActivityDate);
        TO.Included_Holidays__c +=1;    
        }
    }
    update lstTimeOff;
    }
catch(Exception e){
     System.debug('###Exception E :'+ e.getMessage());
            }
 }

And my trigger is:

trigger TimeOffAfterInsert on Time_Off__c (after insert) {
    if(!Trigger.New.isEmpty()){
    TRTimeOffTreatement.MyHolidays(Trigger.New);
}
}

Seems logic but I still have this exception error:

System.NullPointerException: Attempt to de-reference a null object: Class.TRTimeOffTreatement.MyHolidays: line 16, column 1

means this line TO.Included_Holidays__c += lstHolidays.size();

Best Answer

There are these issues with the currently posted code:

  • as this is an "after" trigger, any change you make to Included_Holidays__c will not be persisted; I can't see why this shouldn't be a "before" trigger instead
  • your NullPointerException is probably because TO.Included_Holidays__c starts out null; check if it is null and just assign the value instead in that case
  • you have a query inside a trigger loop which would very likely cause a governor limit to be hit if any kind of bulk insert of Time_Off__c is done
  • you are querying every Time_Off__c at the start of your code (likely to hit a governor limit) instead of just using the list passed in from the trigger

I am not very familiar with the Holiday object but various posts mention that one record can represent a recurring sequence. So you may need to add further logic (and perhaps there is API that can help - BusinessHours.isWithin mentions that it checks holidays).

Related Topic