I have created a trigger that will be executed when the task created or edited.
Scenario: If current date is 22 Jan 2020 and the task due date is is 7thfeb 2020, so in between, there are 2 Saturdays and 2 Sundays, in total 4 holidays so you will extend the date 7th by four days but again 8th and 9th are Saturday and Sunday so the due date will be 13thfeb 2020.
I also created a Custome field Actual Due Date. that have the extended date
Trigger:
trigger ActualDuedate on Task (before insert,before update, after insert, after update)
{
if(trigger.isBefore )
{
if (trigger.isInsert)
{
for(task t: trigger.New)
{
if(t.ActivityDate!=null)
{
integer count=0;
system.debug('Due date is: '+t.ActivityDate);
date endDate=date.newInstance(t.ActivityDate.year(), t.ActivityDate.month(), t.ActivityDate.day());
date startDate=date.newInstance(system.today().year(), system.today().month(), system.today().day());
datetime e= (datetime)endDate;
if(e.format('E')=='Sat')
{
endDate=endDate.addDays(1);
}
for(date d=startDate ; d<=endDate ; d=d.addDays(1))
{
dateTime myDate= (dateTime)d;
string weekName = myDate.format('E');
if(weekName =='Sat' || weekName == 'Sun')
{
count++;
}
}
// if actual Date is also have the sat or sun
dateTime actualdate= (dateTime)endDate.addDays(count);
string weekName2= actualdate.format('E');
if(weekName2 == 'Sat')
{
t.Actual_Due_Date__c=actualdate.addDays(2);
}
else if(weekName2 == 'Sun')
{
t.Actual_Due_Date__c=actualdate.addDays(1);
}
else
{
t.Actual_Due_Date__c=actualdate;
}
}
}
}
if (trigger.isupdate)
{
system.debug('Update Trigger');
for(task t: trigger.New)
{
if(t.ActivityDate!=null)
{
integer count=0;
system.debug('Due date is: '+t.ActivityDate);
date endDate=date.newInstance(t.ActivityDate.year(), t.ActivityDate.month(), t.ActivityDate.day());
date startDate=date.newInstance(t.CreatedDate.year(), t.CreatedDate.month(), t.CreatedDate.day());
system.debug('Start date: '+startDate);
system.debug('EndDate: '+endDate);
datetime e= (datetime)endDate;
if(e.format('E')=='Sat')
{
endDate=endDate.addDays(1);
}
for(date d=startDate ; d <= endDate ; d=d.addDays(1))
{
dateTime myDate= (dateTime)d;
string weekName = myDate.format('E');
if(weekName =='Sat' || weekName == 'Sun')
{
count++;
}
}
system.debug('count :'+count);
// if actual Date is also have the sat or sun
dateTime actualdate= (dateTime)endDate.addDays(count);
string weekName2= actualdate.format('E');
if(weekName2 == 'Sat')
{
t.Actual_Due_Date__c=actualdate.addDays(2);
}
else if(weekName2 == 'Sun')
{
t.Actual_Due_Date__c=actualdate.addDays(1);
}
else
{
t.Actual_Due_Date__c=actualdate;
}
}
}
}
}
}
ref: ak@infoglen.com
No comments:
Post a Comment