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;
}
2 Answers
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.
-
-
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 WCommented Apr 4, 2022 at 10:50
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 ||
-
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 WCommented Apr 4, 2022 at 9:42
-
startDate
) is NOT a Saturday or Sunday and only then incrementing the total.