Skip to content

Instantly share code, notes, and snippets.

@conrjac
Last active July 5, 2016 08:56
Show Gist options
  • Save conrjac/8a803eb5319ad08e50e07f41c1b846be to your computer and use it in GitHub Desktop.
Save conrjac/8a803eb5319ad08e50e07f41c1b846be to your computer and use it in GitHub Desktop.
Add working days to a date in SalesForce, taking into account weekends and company holidays
global class DateHelper {
public static Date addBussinessDays(Date startDate, Integer iDays)
{
Integer businessDaysAdded = 0;
Date currentDate = startDate;
while (businessDaysAdded < iDays) {
currentDate = currentDate.addDays(1);
Datetime d = datetime.newInstance(currentDate.year(), currentDate.month(),currentDate.day());
if (d.format('E') != 'Sat' && d.format('E') != 'Sun' && checkifItisWorkingDay(currentDate)) {
// it's a business day, so add 1 to the counter that works towards the amount of days to add
businessDaysAdded = businessDaysAdded + 1;
}
}
return currentDate;
}
public static List<Holiday> holidays {
get {
if(holidays == null)
holidays=[Select h.StartTimeInMinutes, h.Name, h.ActivityDate From Holiday h];
return holidays;
}
private set;
}
public static boolean checkifItisWorkingDay(Date currentDate){
Date weekStart = currentDate.toStartofWeek();
for(Holiday hDay:holidays){
if(currentDate.daysBetween(hDay.ActivityDate) == 0){
return false;
}
}
datetime predicatedDateTime = datetime.newInstance(currentDate.year(), currentDate.month(), currentDate.day());
// if date fall in weekend return false
if(predicatedDateTime.format('E') == 'Sat' | predicatedDateTime.format('E') == 'Sun'){
return false;
}
else
return true;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment