ShowAll Questionssorted byDate Posted
Justin 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>();
busHoursList  = [SELECT ID FROM BusinessHours WHERE isActive = TRUE ORDER BY LastModifiedDate DESC LIMIT 1];
if(busHoursList.size()>0){
try{
Date startDateMonth = Date.Today().toStartofMonth();
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){
}
if(!accountList.isEmpty()){
update accountList;
}
}catch(DmlException dmlExcep){
//Do Nothing
}
catch(Exception excep){
//Do Nothing
}
}
}
}
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') {