Friday, May 9, 2014

Calculate Nth Business Day using Apex in Salesforce.com

It's been a year since I've posted anything on my blog. I've been busy with a lot of custom development on force.com. :)

You might run into a situation where you have to calculate the Nth working days from a specified date.
You will find this post very useful to calculate Nth business day from a given date.

My client has a Service Level Agreement (SLA) requirements in which they need to act on customer complaints within N business days depending upon the severity.

So I came up with the following apex code to determine the Nth business day from a given date. (This APEX CODE Utilize the Holiday object.)
It's pretty straight forward, and it might come in handy for you.

To setup holidays Go to : Administrative setup > Company Profile > Holidays> add few entries e.g. 26th May 2014 >Memorial Day

Apex code is as below:

 //to calculate Nth business day 
    public static Date calculateNthWorkingDay(Date fromDate, Integer N){

         //Query hoildays from Org  
                List<Holiday> holidays=[Select StartTimeInMinutes, Name, ActivityDate From Holiday ];

                Date NthDay = fromDate; 
                
                for(Integer k=0;k<N ;k++ ){
                    if(checkifWorkDay(NthDay.addDays(1),holidays)){                        
                        NthDay = NthDay.addDays(1);
                    } 
                    else
                    {
                      NthDay = NthDay.addDays(1);
                      K--;
                    }
                }

                return NthDay;//send Nth Business day

      }

    //To check if sent date is a working day by comparing with org holidays
  public static boolean checkifWorkDay(Date sentDate,List<Holiday> holidays){
    
                Date weekStart  = sentDate.toStartofWeek();
                
                for(Holiday hday:holidays){
                        if(sentDate.daysBetween(hday.ActivityDate) == 0)                        
                        return false;                        
                }
                
                if(weekStart.daysBetween(sentDate) ==0 || weekStart.daysBetween(sentDate) == 6)
                {
                       return false;
                } else 
                       return true;
    }

Add these methods in your apex class. lets say name of the apex class > Your_APEX_Class_Name

In order to get 10th business day from today call this method as follows:

date nday = Your_APEX_Class_Name.calculateNthWorkingDay(system.today(),10 );
system.debug('nday is**'+nday);

Hope you will find this code useful.

Thanks,
Rahul G