ShowAll Questionssorted byDate Posted
SFDC_shubh

# Create a function which take 2 dates as argument and return number of working days between two days excluding both days(Saturday and Sunday is nonworking) ?

Andrew G
A quick google reveals:
as formula
as Apex

Regards
Andrew G
Ajay K Dubedi
Hi Shubham,

To find no. of days betweeen two dates use this code:

public class Datedifference {
public static Integer datemethod(Date d1,Date d2)
{
Date startDate = Date.newInstance(2008, 1, 1);
Date dueDate = Date.newInstance(2008, 1, 30);
Integer numberDaysDue = startDate.daysBetween(dueDate);
System.debug('date differnce'+numberDaysDue);
return numberDaysDue;

}
}

To find days between two dates excluding  Saturday and Sunday do follow the code below:

private static final List<Boolean> isWorkingDay;

private static final Integer workingDaysInWeek;
static {

isWorkingDay = new List<Boolean> { true, true, true, true, true, false, false };

workingDaysInWeek = 5;
}

private static final Date monday = Date.newInstance(1900, 1, 3);
private static Integer getDayOfWeek(Date value) {
return Math.mod(monday.daysBetween(value), 7);
}

public static Integer getWorkingDays(Date startDate, Date endDate) {
//save some calculations when the number of working days is 0
if(workingDaysInWeek == 0 || startDate == null || endDate == null) {
return 0;
} else {
Integer difference = startDate.daysBetween(endDate);
if(difference == 0) {
//If the 2 dates are the same day check if the day is a working day or not
return isWorkingDay[getDayOfWeek(startDate)] ? 1 : 0;
} else if(workingDaysInWeek == 7) {
//when every day is a working day return the difference
return difference;
} else {

Integer wholeWeeks = Math.floor(difference / 7).intValue();
Integer workingDays = wholeWeeks * workingDaysInWeek;
Integer dayOfWeek = getDayOfWeek(endDate);
for(Integer remainder = Math.mod(difference, 7); remainder >= 0; remainder--) {
if(isWorkingDay[dayOfWeek]) {
workingDays++;
}
dayOfWeek--;
if(dayOfWeek < 0) {
dayOfWeek = 6;
}
}
return workingDays;
}
}
}

Thanks.Please mark as Best Answer if you find it helpful.
Ajay Dubedi