Taking advantage of the fact that end of month X
is the day before the first of month (X + 1)
, and using MOD()
to handle the month rolling over into the new year:
CASE(
Payment_Terms__c,
'Net', DATE( YEAR(TODAY()) + IF( MONTH(TODAY()) > 11, 1, 0), MOD( MONTH(TODAY()) + 0, 12) + 1, 1) - 1,
'Net 30', DATE( YEAR(TODAY()) + IF( MONTH(TODAY()) > 10, 1, 0), MOD( MONTH(TODAY()) + 1, 12) + 1, 1) - 1,
'Net 60', DATE( YEAR(TODAY()) + IF( MONTH(TODAY()) > 9, 1, 0), MOD( MONTH(TODAY()) + 2, 12) + 1, 1) - 1,
'Net 90', DATE( YEAR(TODAY()) + IF( MONTH(TODAY()) > 8, 1, 0), MOD( MONTH(TODAY()) + 3, 12) + 1, 1) - 1,
'Net 120', DATE( YEAR(TODAY()) + IF( MONTH(TODAY()) > 7, 1, 0), MOD( MONTH(TODAY()) + 4, 12) + 1, 1) - 1,
'30', TODAY() + 30,
'60', TODAY() + 60,
'90', TODAY() + 90,
TODAY()
)
So, for Net
terms where we want the end of the current month, we find the start of next month and subtract 1 from it to get the end of this month:
YEAR(TODAY()) + IF( MONTH(TODAY()) > 11, 1, 0)
: next year if it's December, otherwise this year.
MOD( MONTH(TODAY()) + 0, 12) + 1
: next month, rolling from 12 to 1
DATE( Y, M, 1) - 1
: the last day of the previous month
The Salesforce date-handling routines take care of knowing what the previous month was (even if it's in the previous year) and how many days it has (even on leap years).
The following terms just repeat the same pattern.
I have found the solution with below code and it will executed perfect.
public static Date calculateWeekDaysforReleaseDateTarget(Date EstimatedDate, Integer targetDays){
Date ReleaseDate = EstimatedDate.addDays(-targetDays);
Integer nonWorkingDays = 0;
Integer currentDay;
for(Integer i=0; i <= ReleaseDate.daysBetween(EstimatedDate); i++) {
currentDay = Math.MOD(Date.newInstance(1990,1,7).daysBetween(ReleaseDate.addDays(i)),7);
if(currentDay == 6 || currentDay == 0) {
nonWorkingDays++;
}
}
ReleaseDate = ReleaseDate.addDays(-nonWorkingDays);
Datetime dt = DateTime.newInstance(ReleaseDate.year(), ReleaseDate.month(), ReleaseDate.day());
if(dt.format('E') == 'Sat'){
ReleaseDate = ReleaseDate.adddays(-1);
}
else if(dt.format('E') == 'Sun'){
ReleaseDate = ReleaseDate.adddays(-2);
}
return ReleaseDate;
}
Best Answer
You know the year so can create a DATE for Jan 1st and then add your day offset. Using your example you would create the date using
DATE(2015, 1, 1)
and then add 89 (90 - 1) days.You don't need to handle leap years using this approach.