+ Start a Discussion
TheLearnerTheLearner 

Trigger for calculating the bank working days and non working days

HI Experts,

Hi Experts,
 
There is requriment i need to write trigger based on this checkbox condition.There object called bank(bank__c) in that based on field values
If Non Working Day = Check (true) then Estimate Start Date(Estimate_Start_Date__c), Estimate End Date(Estimate_End_Date__c), Actual Start Date(Actual_Start_Date__c), Target Stop(Target_stop__c) and Work Stop(Work_Stop__c) can be any date including non working days (i.e. Monday to Friday, Saturday, Sunday or Bank Holiday). If Non Working Day = Unchecked (false) then Estimated Start Date, Estimated End Date, Actual Start Date, Target Stop and Work Stop can only be working day (i.e. Monday to Friday excluding bank holidays).
Could anyone help me to write trigger on this please
Abhishek BansalAbhishek Bansal
Hi ,

Please find the code of your trigger below :
 
trigger checkWeekends on Bank__c (before insert, before update{
	for(Bank__c newBankRecord : trigger.new){
		if(!newBankRecord.Non_Working_Day__c){//Please replace Non_Working_Day__c with original API name of field
			if(((DateTime)newBankRecord.Estimate_Start_Date__c).format('E') == 'Sat' || ((DateTime)newBankRecord.Estimate_Start_Date__c).format('E') == 'Sun'){
				newBankRecord.addError('Estimated start date must be a Weekday');
			}
			else if(((DateTime)newBankRecord.Estimate_End_Date__c).format('E') == 'Sat' || ((DateTime)newBankRecord.Estimate_End_Date__c).format('E') == 'Sun'){
				newBankRecord.addError('Estimated End date must be a Weekday');
			}
			else if(((DateTime)newBankRecord.Actual_Start_Date__c).format('E') == 'Sat' || ((DateTime)newBankRecord.Actual_Start_Date__c).format('E') == 'Sun'){
				newBankRecord.addError('Actual start date must be a Weekday');
			}
			else if(((DateTime)newBankRecord.Target_stop__c).format('E') == 'Sat' || ((DateTime)newBankRecord.Target_stop__c).format('E') == 'Sun'){
				newBankRecord.addError('Target Stop date must be a Weekday');
			}
			else if(((DateTime)newBankRecord.Work_Stop__c).format('E') == 'Sat' || ((DateTime)newBankRecord.Work_Stop__c).format('E') == 'Sun'){
				newBankRecord.addError('Work Stop date must be a Weekday');
			}
		}
	}
}
We can find out the weekends from above logic but it is impossible to find bank holidays as they are not fixed and may vary from time to time.
The above mentioned logic will only validate the weekends.

NOTE : Please replace the variables with your original API name.

Let me know if you have any issue or you want any modification in trigger.

Regards,
Abhishek
TheLearnerTheLearner
HI Abhishek,

Thanks for the reply here now working day is check box field .
TheLearnerTheLearner
HI Abhishek,


Thanks for the reply here now working day is check box field and if its checked we need include the anydate of non working day in the fields which i mentioned above, if it is unchecked its need to working day date in the above fields.
 
Abhishek BansalAbhishek Bansal
Hi, Yes i know what you want to achiece. The trigger written above will fire a validation if checkbox is not checked and user enters weekend date in any of the field mentioned above. If the checkbox is checked that user can enter any values so this trigger will not fire any validation. Please let me know if your requirements are different from what i am thinking and if possible please provide a live example explaining your requirements. Regards, Abhishek
srikanth yalaboinasrikanth yalaboina
Hi abhishek,if(((DateTime)newBankRecord.Estimate_Start_Date__c).format('E') == 'Sat' 
Could u pls explain the above statement
Abhishek BansalAbhishek Bansal
Hi Srikant,

The statement which you mentioned above will return true if the date entered in "Estimate_Start_Date__c" is a Saturday.
It will return false if the date entered in "Estimate_Start_Date__c" is not a Saturday.

Let me know if you need more clarification on this.

Regards,
Abhishek.
TheLearnerTheLearner
HI Abhishek,

ya exactly that is my requirment, but im confused why you used E int eh format method . could you tell me please
if(((DateTime)newBankRecord.Estimate_Start_Date__c).format('E')
 
Abhishek BansalAbhishek Bansal
Hi,

These are the standard methods of DateTime class to find out the day from a given datetime field.
You can find out the complete infromation about these methods on link given below.

https://developer.salesforce.com/docs/atlas.en-us.apexcode.meta/apexcode/apex_methods_system_datetime.htm

If you don not have any further queries on this question than please close this question by marking it as SOLVED so that it can help others to find as olution for them.

Thanks,
Abhishek
TheLearnerTheLearner
Hi Abhishek,

There is object called HOlidaylist which contain all the holidays dates im posting those holidays as well, there is class which calculate the working days only, we need to calculate the nonworking days and holidays and sunday and saturday. this is the code for working days could you help me how to write for nonworkings and how we need to use in our trigger plesae. 


//CH01:  Created new method to calculate the finish date , If the End date rerurn by function is Holiday.
//CH02:Added new method to calculte no of days without holidays and weekends for bulk record
public with sharing class Holidaynewlist{
    
    public static Integer CalculatedDaysToFinishDateWithoutWeekendsAndHolidays(Date startDate, Date endDate){
    Integer addedDays = startDate.daysBetween(endDate);
    Integer addedDaysCopy = startDate.daysBetween(endDate);
    Date currentDay;
    Integer lastDay=0;
    List<Holiday_List__c> ShutdownDaysInRange = [select Holiday_Date__c from Holiday_List__c where  Holiday_Date__c >=: startDate order by  Holiday_Date__c];
    System.debug('Holiday List: '+ShutdownDaysInRange );
    Boolean isWeekendDay;
    Boolean isShutdownDay;
    Integer i=0;
    Date shutdownDay = null;
    Integer delholiday =0;
    set<integer> holIndex = new  set<integer>();
    
    //Excluding Holiday if Start Date is helding on Holidays
    if(ShutdownDaysInRange.size()>0){
    if(startDate == ShutdownDaysInRange[0].Holiday_Date__c){
        for(Holiday_List__c hd1 : ShutdownDaysInRange ){
            if(startDate == hd1.Holiday_Date__c ){
                startDate = startDate.addDays(1);
                addedDays = addedDays-1;
                addedDaysCopy = addedDaysCopy -1;
                holIndex.add(delholiday);
                }
                 delholiday++;
            }
            for(integer dd1 : holIndex ){
                ShutdownDaysInRange.remove(dd1);
            }   
        }
    }
     
            Integer intDayOfWeek = Holidaylist.DayOfWeek(startDate);
            
            //Excluding Weekend if Start Date is helding on Weekend
            if( intDayOfWeek == 6 || intDayOfWeek == 0){
            if(intDayOfWeek == 6){
                addedDays = addedDays-2;
                addedDaysCopy = addedDaysCopy -2;
                startDate = startDate.addDays(2);
                intDayOfWeek = 1;
            }
            
                else if(intDayOfWeek == 0){
                    addedDays = addedDays-1;
                    addedDaysCopy = addedDaysCopy -1;
                    startDate = startDate.addDays(1);
                    intDayOfWeek = 1;
                }
                 
                delholiday = 0; 
                holIndex = new  set<integer>();
                for(Holiday_List__c hh : ShutdownDaysInRange ){
                    if(startDate == hh.Holiday_Date__c ){
                        startDate = startDate.addDays(1);
                        addedDays = addedDays-1;
                        addedDaysCopy = addedDaysCopy -1;
                        intDayOfWeek = intDayOfWeek +1;
                        holIndex.add(delholiday);
                    }
                        delholiday++;
                }
                for(integer dd : holIndex  ){
                    ShutdownDaysInRange.remove(dd);
                }
            }
            
            
          //  Calculating from Working day to Working Day
           if (!ShutdownDaysInRange.isEmpty()){
                 shutdownDay = ShutdownDaysInRange[i].Holiday_Date__c;
            }
                
            for(Integer x=1;x<=addedDays;x++){
                isShutdownDay = false;
                isWeekendDay = false;
                currentDay = startDate.addDays(x);
                System.debug('==>> Added Days Copy = '+addedDaysCopy);
                if (intDayofWeek==6) //if saturday
                    intDayOfWeek = 0;    //= sunday
                else
                    intDayOfWeek= intDayOfWeek+1;
                System.debug('==>> Day of Week + Current Day + Shutdownday =   '+intDayOfWeek+'   '+currentDay+'    '+shutdownday); 
                if(intDayOfWeek==0||intDayOfWeek==6){
                    
                    addedDaysCopy--;
                    isWeekendDay = true;
                }
                else{
                    if(shutdownday!=null){
                           
                    if (shutdownday.isSameDay(currentDay)){
                        
                        addedDaysCopy--;
                        isShutdownDay = true;
                        i++;
                        if(i<ShutdownDaysInRange.size()){
                            shutdownDay = ShutdownDaysInRange[i].Holiday_Date__c;
                                            
                            }
                        else{
                                
                            shutdownDay = null;
                            }    
                        }
                    }
                }
                if(!isShutdownDay&&!isWeekendDay){
                    if(x!=addedDays){
                    lastDay = x;   
                    
                    } 
                } 
            }
            if(addedDaysCopy >= -1)
             return addedDaysCopy+1;
             return 1;
    
}
 /*CH01 Start */
 public static Date CalculatedFinishDate(Date startDate, Double duration){
    List<Holiday_List__c> ShutdownDaysInRange = [select Holiday_Date__c from Holiday_List__c where  Holiday_Date__c >=: startDate order by  Holiday_Date__c];
    Set<Date> HolDate = new Set<Date>();
    for(Holiday_List__c obj: ShutdownDaysInRange)
        HolDate.add(obj.Holiday_Date__c);
    date s = startDate;
    Integer intDayOfWeek = DayOfWeek(s);
    boolean isStartDateHoliday = false;
    while(HolDate.contains(s) || intDayOfWeek == 0 || intDayOfWeek == 6){
        s = s.addDays(1);
        intDayOfWeek = DayOfWeek(s);
        isStartDateHoliday = true;
    }
    integer addedDays = integer.valueof(duration);
    integer count = 0;
    date finalStartDate = s;
    date finalEndDate = s;
    Integer intDayOfWeekLast;
    if(isStartDateHoliday)
       addedDays--; 
    //date last = s;
    for(integer i=1; i<=addedDays; i++){
        System.debug('I: '+i);
        System.debug('addedDays: '+addedDays);
        system.debug('previous finalEndDate: '+finalEndDate);
        finalEndDate = finalEndDate.addDays(1);
        intDayOfWeekLast = DayOfWeek(finalEndDate);
        system.debug('day of week: '+intDayOfWeekLast);
        //boolean isWhile = false;
        while(HolDate.contains(finalEndDate) || intDayOfWeekLast == 0 || intDayOfWeekLast == 6){
            finalEndDate = finalEndDate.addDays(1);
            intDayOfWeekLast = DayOfWeek(finalEndDate);
            System.debug('While final: '+finalEndDate);
            //isWhile = true;
            //addedDays++;
        }
        /*if(!isWhile)
        finalEndDate = finalEndDate.addDays(1);*/
        if(i == addedDays && (HolDate.contains(finalEndDate) || intDayOfWeekLast == 0 || intDayOfWeekLast == 6)){
            addedDays++;
            System.debug('finalEndDate: '+finalEndDate);
            integer intDayOfWeekLast1 = DayOfWeek(finalEndDate);
            System.debug('intDayOfWeekLast1  : '+intDayOfWeekLast1 );
            System.debug('addedDays 1 : '+ addedDays);
        }
    }
    return finalEndDate;
}

      private static Integer getMonthTableValue(integer month){
        integer monthTableValue;
        if (month == 1) monthTableValue = 0 ; 
        if (month == 2) monthTableValue = 3;
        if (month == 3) monthTableValue = 3;
        if (month == 4) monthTableValue = 6;
        if (month == 5) monthTableValue = 1;
        if (month == 6) monthTableValue = 4;
        if (month == 7) monthTableValue = 6;
        if (month == 8) monthTableValue = 2;
        if (month == 9) monthTableValue = 5;
        if (month == 10) monthTableValue = 0;
        if (month == 11) monthTableValue = 3;
        if (month == 12) monthTableValue = 5;
        return monthTableValue;
    }//end method
 //Function calculates the day of the week 0=sunday 
    public static Integer DayOfWeek(Date x){
        Double a;
        Double b;
        Double c;
        Double d;
        Long e;
        Long z = 7;
        
        a = math.floor(x.year() / 4);
        b = math.floor(x.year() / 100);
        c = math.floor(x.year() / 400);
        d = x.year() + a - b + c -1 + getMonthTableValue(x.month())+x.day();
        e = math.mod(math.roundtoLong(d),z);
        
        return math.floor(e).intValue();
    }
   /*CH01 End */
   
   //CH02.start
   /*
        bulkCalculatedDaysToFinishDateWithoutWeekendsAndHolidays() - This method is used to calculate no of days between start date and end date
                                without weekend and holidays.           
   */
   public static Integer bulkCalculatedDaysToFinishDateWithoutWeekendsAndHolidays(list<Holiday_List__c> lstHol,Date startDate, Date endDate){
        list<Holiday_List__c> ShutdownDaysInRange = new list<Holiday_List__c>();
        for(Holiday_List__c objHol : lstHol){
            if(objHol.Holiday_Date__c >= startDate)
                ShutdownDaysInRange.add(objHol);
        }
        Integer addedDays = startDate.daysBetween(endDate);
        Integer addedDaysCopy = startDate.daysBetween(endDate);
        Date currentDay;
        Integer lastDay=0;
        //List<Holiday_List__c> ShutdownDaysInRange = [select Holiday_Date__c from Holiday_List__c where  Holiday_Date__c >=: startDate order by  Holiday_Date__c];
        System.debug('Holiday List: '+ShutdownDaysInRange );
        Boolean isWeekendDay;
        Boolean isShutdownDay;
        Integer i=0;
        Date shutdownDay = null;
        Integer delholiday =0;
        set<integer> holIndex = new  set<integer>();
        
        //Excluding Holiday if Start Date is helding on Holidays
        if(ShutdownDaysInRange.size()>0){
            if(startDate == ShutdownDaysInRange[0].Holiday_Date__c){
                for(Holiday_List__c hd1 : ShutdownDaysInRange ){
                    if(startDate == hd1.Holiday_Date__c ){
                        startDate = startDate.addDays(1);
                        addedDays = addedDays-1;
                        addedDaysCopy = addedDaysCopy -1;
                        holIndex.add(delholiday);
                    }
                    delholiday++;
                }
                for(integer dd1 : holIndex ){
                    ShutdownDaysInRange.remove(dd1);
                }   
            }
        }
         
        Integer intDayOfWeek = DayOfWeek(startDate);
        
        //Excluding Weekend if Start Date is held on Weekend
        if( intDayOfWeek == 6 || intDayOfWeek == 0){
        if(intDayOfWeek == 6){
            addedDays = addedDays-2;
            addedDaysCopy = addedDaysCopy -2;
            startDate = startDate.addDays(2);
            intDayOfWeek = 1;
        }
        
            else if(intDayOfWeek == 0){
                addedDays = addedDays-1;
                addedDaysCopy = addedDaysCopy -1;
                startDate = startDate.addDays(1);
                intDayOfWeek = 1;
            }
             
            delholiday = 0; 
            holIndex = new  set<integer>();
            for(Holiday_List__c hh : ShutdownDaysInRange ){
                if(startDate == hh.Holiday_Date__c ){
                    startDate = startDate.addDays(1);
                    addedDays = addedDays-1;
                    addedDaysCopy = addedDaysCopy -1;
                    intDayOfWeek = intDayOfWeek +1;
                    holIndex.add(delholiday);
                }
                    delholiday++;
            }
            for(integer dd : holIndex  ){
                ShutdownDaysInRange.remove(dd);
            }
        }
        
        
       //  Calculating from Working day to Working Day
       if (!ShutdownDaysInRange.isEmpty()){
             shutdownDay = ShutdownDaysInRange[i].Holiday_Date__c;
        }
            
        for(Integer x=1;x<=addedDays;x++){
            isShutdownDay = false;
            isWeekendDay = false;
            currentDay = startDate.addDays(x);
            System.debug('==>> Added Days Copy = '+addedDaysCopy);
            if (intDayofWeek==6) //if saturday
                intDayOfWeek = 0;    //= sunday
            else
                intDayOfWeek= intDayOfWeek+1;
            System.debug('==>> Day of Week + Current Day + Shutdownday =   '+intDayOfWeek+'   '+currentDay+'    '+shutdownday); 
            if(intDayOfWeek==0||intDayOfWeek==6){
                
                addedDaysCopy--;
                isWeekendDay = true;
            }
            else{
                if(shutdownday!=null){
                    if (shutdownday.isSameDay(currentDay)){
                        addedDaysCopy--;
                        isShutdownDay = true;
                        i++;
                        if(i<ShutdownDaysInRange.size()){
                            shutdownDay = ShutdownDaysInRange[i].Holiday_Date__c;
                            }
                        else{
                            shutdownDay = null;
                            }    
                    }
                }
            }
            if(!isShutdownDay&&!isWeekendDay){
                if(x!=addedDays){
                    lastDay = x;   
                } 
            } 
        }
        if(addedDaysCopy >= -1)
         return addedDaysCopy+1;
         return 1;
    }
    
    /*
        bulkCalculateDaysBetweenDatesWithoutHolidaysOnly() -- This method is used to calculate no of days between start date and end date
                                without holidays.  
    */
    public static Integer bulkCalculateDaysBetweenDatesWithoutHolidaysOnly(list<Holiday_List__c> lstHol,Date startDate, Date endDate){
        Set<Date> HolDate = new Set<Date>();
        for(Holiday_List__c objHol : lstHol){
            if(objHol.Holiday_Date__c >= startDate)
                HolDate.add(objHol.Holiday_Date__c);
        }
        Integer addedDays = startDate.daysBetween(endDate);
        Integer addedDaysCopy = startDate.daysBetween(endDate) + 1;
        date finalEndDate = startDate;
        for(integer i=0; i<=addedDays; i++){
            if(HolDate.contains(finalEndDate))
                addedDaysCopy--;
            finalEndDate = finalEndDate.addDays(1);
        }
        return addedDaysCopy;
    }
   
    
    }          
}

User-added image
 
TheLearnerTheLearner
Hi Abhishek,

is this possible to calcualte workign days and Nonworkings with the object Holiday_List__c
(fields are Holiday Date(Holiday_Date__c),Holiday for(Holiday_for__c)(fields are NA).
If yes please let me know.