• SalesforceDevku
  • NEWBIE
  • 0 Points
  • Member since 2013

  • Chatter
    Feed
  • 0
    Best Answers
  • 0
    Likes Received
  • 0
    Likes Given
  • 0
    Questions
  • 1
    Replies

Given the Start Date and No. of Business days  find ending date, if you pass a negative amount of days then should get Current Date less those business days,

 

Already test it and currently using it, feel free to correct or improve it for sharing

 

    public static Boolean IsWeekendDay(Datetime dateParam)
    {
       boolean result     = false;
        
       //Recover the day of the week
       Date startOfWeek   = dateParam.date().toStartOfWeek();
       Integer dayOfWeek  = dateParam.day() - startOfWeek.day();
           
       result = dayOfWeek == 0 || dayOfWeek == 6 ? true : false;
        
       return result;
    } 
    
    
    public static Datetime AddBusinessDays(Datetime StartDate, integer BusinessDaysToAdd )
    {
       //Add or decrease in BusinessDaysToAdd days 
       Datetime finalDate = StartDate;
       
       integer direction = BusinessDaysToAdd < 0 ? -1 : 1;

        while(BusinessDaysToAdd != 0)
        {
            finalDate = finalDate.AddDays(direction);            
            
            if (!isWeekendDay(finalDate))
            {
                BusinessDaysToAdd -= direction;
            }
        }

        return finalDate;
    }