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
degmodegmo 

Date formula help

Hi,
I have two custom date fields on the account object.  Signup_Date and Contact_Date.  The requirement I have says, if the Signup_Date is greater than 45 calendar days from today, I need to make sure the Contact_Date is Signup_Date minus 45 calendar days.  One important caveat is I have to make sure that Signup_Date minus 45 calendar day doesn't fall on a weekend.  If it falls on Saturday, I need to set it to the Friday before and if it is on a Sunday, i need to set it to the Monday after.  I am struggling with this and hoping somebody can assist me.
Best Answer chosen by degmo
ANUTEJANUTEJ (Salesforce Developers) 
Hi Degmo,

I think you can have a trigger that works on before insert and you can make use of below code and modify it as per your use case.
 
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;
    }

reference: https://salesforce.stackexchange.com/questions/91916/subtract-date-days-from-number-except-weekend-days-using-apex-class

Let me know if it helps you and close your query by marking it as solved so that it can help others in the future.  

Thanks.