function readOnly(count){ }
Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
+ Start a Discussion
Justin Cairns 9Justin Cairns 9 

Calculate Number of Business Days in a Month - APEX

We have a batch process that updates the # of business days in the current month on our account records.  It is returning a value of 21 for January even though the number of business days in January is 22.  We don't have any holidays built in our system for January.  Any suggestions as to what we are doing wrong would be appreciated.  

 global void execute(Database.BatchableContext BC, List<Account> scope) {
    
        if(scope.size()>0){
            list<Account> accountList = new list<Account>();
            list<BusinessHours> busHoursList = new list<BusinessHours>();
            busHoursList  = [SELECT ID FROM BusinessHours WHERE isActive = TRUE ORDER BY LastModifiedDate DESC LIMIT 1];
            if(busHoursList.size()>0){
                try{                
                    Date startDateMonth = Date.Today().toStartofMonth();
                    Date endDateMonth   = startDateMonth.addMonths(1).addDays(-1);
                    DateTime startTime = DateTime.newInstance(startDateMonth.year(), startDateMonth.month(), startDateMonth.day());
                    DateTime endTime = DateTime.newInstance(endDateMonth.year(), endDateMonth.month(), endDateMonth.day());
                    Decimal noOfWorkingDays = BusinessHours.diff(busHoursList[0].Id, startTime, endTime)/(3600*1000*24);
                    for(Account accObj : scope){
                        accObj.TAFS_Total_Business_Days_This_Month__c = noOfWorkingDays;
                        accountList.add(accObj);
                    }
                    if(!accountList.isEmpty()){
                        update accountList;
                    }                    
                }catch(DmlException dmlExcep){
                    //Do Nothing
                }
                catch(Exception excep){
                    //Do Nothing
                }           
            }               
        }
    }
George AdamsGeorge Adams
This returns the correct number. Might be useful to you.
 
Date d1 = Date.Today().toStartofMonth();
Date d2 = d1.addMonths(1);

Set<Date> daySet = new Set<Date>();

while(d1 < d2)
{
    Datetime dtime = datetime.newInstance(d1.year(), d1.month(),d1.day());
    if (dtime.format('E') != 'Sat' && dtime.format('E') != 'Sun') {
        daySet.add(d1);
    }
    d1 = d1.AddDays(1);
}

System.Debug('###: ' + daySet.size());

 
Justin Cairns 9Justin Cairns 9
Would you be able to account for the Holidays we have defined?  I know that using Business Hours counts for holidays, but for whatever reason it's correct some months and incorrect others.