Calcuate weekends / weekdays in Apex


I’ve been having lots of fun with dates and datetime in Apex lately, and thought it might be useful to post a simple function I wrote. This function might come in handy if you’re working with a date range for calculations and want to exclude weekends – pass it a start & end date and it will return an integer value of the number of days off (important to note that this function returns the number of days off – not the number of working days).

public static Integer daysOff(Datetime sdate, Datetime edate)
         Integer i = 0;
         while (sdate < edate) {
           if (sdate.format('E') == 'Sat' | sdate.format('E') == 'Sun'){
             i = i + 1;
         sdate = sdate.addDays(1);
         return i;

To calculate the number of working days just get the total number of days between a range, and subtract the number of days off:

//Get the number of days between date range
Integer totalnumberDays = sdate.daysBetween(edate);

//Get number working days
Integer workingdays = (totalnumberDays - daysOff(01/01/2009, 01/10/2009));

Note that for those of you working in regions where the weekend is not Saturday and Sunday, simply change ‘Sat’ and ‘Sun’ to the relevant day(s) of the week.

  • David Latham


    This looks very promising.

    I need to report on time spent on particular types of activities each month against the number of available "business" hours in that month.

    I had this idea where i could use a trigger to populate a custom field with the number of available hours for the month as determined by the start date of the meeting. Every event during the month will show the same total of available hours, but then in my reporting I could use that field some how.

    Is there a better way to store a custom table of available hours for each month and use that data in a report? IE: Report on November -> Call up available hours from database table -> report time spent on event types against available hours?

    Thanks for your help. – even a pointer in the right direction would be very useful for me. I am fresh out of ideas.