Wednesday, December 12, 2012

Days between two DateTime values excluding weekends

Given two DateTime values in Apex, how many weekdays are there between the two?

Getting the total number of days is straight forward using Date.daysBetween(). Excluding the weekends requires a bit more work.

One possible solution is to just loop through all the dates between the two values and count any that aren't Saturday or Sunday. It's a bit crude and will be expensive if the dates are far apart. It should however work through pure brute force.

    public static Integer daysBetweenExcludingWeekends(Datetime startDate, Datetime endDate) {
        Integer i = 0;

        while (startDate < endDate) {
            if (startDate.format('EEE') != 'Sat' && startDate.format('EEE') != 'Sun') {
                i = i + 1;
            startDate = startDate.addDays(1);
        return i;

See also: