You need to sign in to do that
Don't have an account?
Add business days with Apex
Given the Start Date and No. of Business days find ending date, if you pass a negative amount of days then should get Current Date less those business days,
Already test it and currently using it, feel free to correct or improve it for sharing
public static Boolean IsWeekendDay(Datetime dateParam)
{
boolean result = false;
//Recover the day of the week
Date startOfWeek = dateParam.date().toStartOfWeek();
Integer dayOfWeek = dateParam.day() - startOfWeek.day();
result = dayOfWeek == 0 || dayOfWeek == 6 ? true : false;
return result;
}
public static Datetime AddBusinessDays(Datetime StartDate, integer BusinessDaysToAdd )
{
//Add or decrease in BusinessDaysToAdd days
Datetime finalDate = StartDate;
integer direction = BusinessDaysToAdd < 0 ? -1 : 1;
while(BusinessDaysToAdd != 0)
{
finalDate = finalDate.AddDays(direction);
if (!isWeekendDay(finalDate))
{
BusinessDaysToAdd -= direction;
}
}
return finalDate;
}
I modified this code so you can give a date parameter rather than a datetime parameter.
This code is good, but it required a slight modification.
The reason being the scenario when the Start of the week is 05/28/2013 and the end of the week would be 06/03/2013.
In that case the difference between the dates would be 22. This scenarios would break the above code to check the Weekend day. So i would rather suggest you to use
public static Boolean IsWeekendDay(Date dateParam)
{
boolean result = false;
//Recover the day of the week
Date startOfWeek = dateParam.toStartOfWeek();
Integer dayOfWeek = startOfWeek.daysBetween(dateParam);
result = dayOfWeek == 0 || dayOfWeek == 6 ? true : false;
return result;
}
Good catch, hope it saved some time.
- The problem of being in Europe or US, where the week starts on Monday and on Sunday respectively, thus testing dayOfWeek against 0 or 6 only works for local regions similar to US. What is there now is little 'trick' using a datetime conversion do Date in English language to guarantee we always catch Saturdays and Sundays.
- For last, in the month's crossing the formula wasn't detecting the weekend days, because the StartofWeek would be higher than the dateParam.day(), so in this cases it's necessary to add the total days of the month (in respect to the previous month of that day that we are treating)
Did anyone made a test class for this?