function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
The new LearnerThe new Learner 

correcting the logic to exclude weekends

Hi Experts,
 
I have to populate the Closed date with in the weekdays that is system.today+10 days, can anyone help me out , if I pass system.today(), 10 its showing to 31st, as per the logic it should show May 30th, even I dont know how worst it will behave for weekends when the record is created on weekends.. Below my logic can anyone help me out.
Public class BusinessDayCalculation  
    {
        Public static Date addBussinessDays(Date startDate, Integer iDays)
        {
            Integer businessDaysAdded = 0;
            Date currentDate = startDate;
            while (businessDaysAdded < iDays) {
                currentDate = currentDate.addDays(1);
                Datetime d = datetime.newInstance(currentDate.year(), currentDate.month(),currentDate.day());
                
                if (d.format('E') != 'Sat' && d.format('E') != 'Sun' && checkifItisWorkingDay(currentDate))
                {
         
                    businessDaysAdded = businessDaysAdded + 1;
                } 
            }       
            return currentDate;
        } 
        
        Public static boolean checkifItisWorkingDay(Date currentDate)
        {
            Date weekStart  = currentDate.toStartofWeek();
            if(weekStart.daysBetween(currentDate) ==0 || weekStart.daysBetween(currentDate) == 6)
            {
                return false;
            } 
            else
            {
                return true;
            }
        } 
    }
This is how I am calling above class in the main class
 if(dayOfWeek == 'Sunday')
                    {
                    opportunityToInsert.CloseDate = BusinessDayCalculation.addBussinessDays(myDate ,12);
                    }
                    else if(dayOfWeek == 'Saturday')
                    {
                       opportunityToInsert.CloseDate = BusinessDayCalculation.addBussinessDays(myDate ,11);
                    }
                    else
                    {
                      opportunityToInsert.CloseDate = BusinessDayCalculation.addBussinessDays(myDate,10);
                    }

 
PriyaPriya (Salesforce Developers) 

Hey,

Kindly refer this example to exclude the Weekend :- 

https://www.c-sharpcorner.com/blogs/calculate-working-days-using-apex-in-salesforce

https://sfdcdev.wordpress.com/2011/09/24/handling-holidays-in-salesforce-apex/

If it helps, kindly mark it as the best answer.

Thanks!