0
public static Integer getWorkingDays(Datetime startDate, Datetime endDate)
{
    Integer totalDays = 0;
    while(startDate<=endDate)
    {
        if(startDate.format('E')!='Sat' && startDate.format('E')!='Sun')
        {
            totalDays++;
        }
        startDate = startDate.addDays(1);
    }
    System.debug('Debug Statement :- ' + totalDays + ' Working Days');
    return totalDays;
}
3
  • I want to know what exactly " startDate.format('E')!='Sat' && startDate.format('E')!='Sun' " is doing. Commented Apr 4, 2022 at 9:31
  • It is asking whether the given date (the updated startDate) is NOT a Saturday or Sunday and only then incrementing the total.
    – Phil W
    Commented Apr 4, 2022 at 9:36
  • Side note: You can use BusinessHours to easily calculate working days without potentially expensive loops.
    – sfdcfox
    Commented Apr 5, 2022 at 0:05

2 Answers 2

0

As per the Java SimpleDateFormat link in the Datetime class's format method documentation, the pattern passed to this method allows 'E' which provides the English day name for the given date/time as 3 letters. In a date/time format, use of "E", "EE" or "EEE" generates the three letter short day names while "EEEE" or longer generates the full day names. The day names are always in English.

Thus, this if condition ensures that the (updated) startDate is neither a Saturday nor a Sunday and only then increments the total number of (week days) being counted.

4
  • Thanxs for the information. Commented Apr 4, 2022 at 9:50
  • Can you please tell me if I want to debug the code what should I write? Commented Apr 4, 2022 at 9:55
  • Apex.getWorkingDays(dateTime.now(), dateTime.now()+6); For now I m writing this code but I want to enter date instead of dateTime.now() in startDate and endDate. Commented Apr 4, 2022 at 9:58
  • Call the method using date/times created using Datatime.newInstance and passing in the required parameters.
    – Phil W
    Commented Apr 4, 2022 at 10:50
0

It is asking whether the given date (the updated startDate) is NOT a Saturday AND Sunday and only then incrementing the total.

which is wrong it can only be one so instead of && you should use ||

2
  • The suggestion to use OR (||) is wrong. The need is correctly stated as the start date is NOT Sat and the start date is NOT Sun. Using OR will mean every date is counted because any given date is always either NOT Sat OR NOT Sun.
    – Phil W
    Commented Apr 4, 2022 at 9:42
  • Yes you are right, sorry my bad. Commented Apr 4, 2022 at 9:45

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .