0

I have a problem with adding days when creating Task. I have a simple apex code

newTask.ActivityDate = Date.today().addDays(5);

But what i need to do is to count only business days. Thanks for any advice.

3

you have to have configured business hours you can use. It is necessary to have default one. That configurations defines which days are working.

Use BusinessHours in order to add working days to some date.

public Date addBusinessDaysToToday(Id businessHoursId, Integer businessDays){
    Long range = ((Long)businessDays) * 24 * 60 * 60 * 1000;
    return System.BusinessHours.add(businessHoursId, Date.today(), range).date();
}

first parameter is Id of BusinessHours that defines what days are working, and what not.


in this line Long range = ((Long)businessDays) * 24 * 60 * 60 * 1000; value of milliseconds is calculated, as method add accepts number of milliseconds to add.

businessDays * hours(24) * minutes(60) * seconds(60) * milliseconds(1000)
  • Ok i set up business days from monday to friday. Put the code into my class but i dont know how to call it. I used newTask.ActivityDate = addBusinessDaysToToday(5); but its not working – David Jan 9 at 10:03
  • 1
    @David I showed you how to create method if you are going to use it frequently. in your case: newTask.ActivityDate = System.BusinessHours.add(businessHoursId, Date.today(), ((Long)5) * 24 * 60 * 60 * 1000).date(); Don't forget to query businessHoursId – Oleksandr Berehovskyi Jan 9 at 10:16

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service, privacy policy and cookie policy

Not the answer you're looking for? Browse other questions tagged or ask your own question.