0

I am trying to calculate the end date when a user supplies the number of days.
Issue is How do I take into account weekends and Holidays. I have code to calculate the number of business days when a Start and End date is supplied but I need the End date when the Start date is today and the user supplies the number of Business days that needs to be added to the start date.

Here is my code to return the number of business days. Can I somehow manipulate the below code to return the end date instead of number of business days?

    global static Integer calcBusinessDays(Date varDate){
    
    Set<Date> hSet = new Set<Date>();
   
    for(Holiday cHoliday : [Select newDate from holiday])
    {
        hSet .add(cHoliday.newDate );
    }

    Integer allDays = 0;  
    Integer workingDays = 0;  
    Integer holiDays = 0; 
    Date endDate = System.today()-1;
    Date startDate = varDate.addDays(1);
     
    for(integer i=0; i <= startDate.daysBetween(endDate); i++){  
        Date dt = startDate + i; 
        DateTime currDate = DateTime.newInstance(dt.year(), dt.month(), dt.day());  
        String todayDay = currDate.format('EEEE');  
        if(todayDay != 'Saturday' && todayDay !='Sunday'){  
            allDays = allDays + 1;  
        }  
        if(holidaysSet.contains(dt)){
            holiDays = holiDays + 1; 
        }
        if(allDays != null && allDays >= holiDays ){
            workingDays = allDays - holiDays;  
        }
    }  
    return workingDays;  

---Solution--- Pass in an integer to the method

public BusinessHours businessHours ;  

public futureDateUtils(){    
    businessHours = [SELECT Id FROM BusinessHours WHERE IsDefault = true];
}

    public Datetime getFutureDate(Integer numDays){

    Datetime finalDate = System.today();
    finalDate  = BusinessHours.nextStartDate(businessHours .Id, finalDate );

    for (Integer elapsed = 0; elapsed < numDays; elapsed++)
    {
        finalDate  = finalDate .addDays(1);
      
        if (!BusinessHours.isWithin(businessHours .Id, finalDate ))
        { 
          finalDate = BusinessHours.nextStartDate(businessHours .Id, finalDate );
        }
    }
    return finalDate ;
} 
2
  • Not necessarily related to tweaking the code you already have, but some helpful observations are: 1) The number of business days will never be less than the number of calendar days. 2) For every 7 days in your interval, you're guaranteed to have at least 2 weekend days. Excluding the week(s) that contain the start and end days (which are boundary conditions that need special handling), you will need to add at least MAX(0, (FLOOR((endDate - startDate) / 7) - 2) * 2) days. 3) You only care about adding holidays that are between the start and end dates. 4) This can be made recursive.
    – Derek F
    Jun 16, 2022 at 22:08
  • thanks for the tips Derek, I will try to create a new method with your observations.
    – Phuc
    Jun 17, 2022 at 13:49

0

Browse other questions tagged .