5

I am getting a CPU timeout from my loop. I have checked the debug logs and my start and end dates have the correct dates in them. I have tried setting the condition to be dtoday.adddays(3) just as a test and got the same result. What am I not seeing?

List<Date> allDays = new list<Date>(); 
Date dToday = system.today();

date currentDay  = dToday.toStartOfMonth(); 
System.debug('CurrentDate = '+currentDay );     
date lastDay = dToday.toStartOfMonth().addMonths(1).addDays(-1);  
System.debug('LastDay = '+lastDay );    

while (currentDay < lastday) {
    allDays.add(currentDay);
    currentDay.addDays(1);
} 
system.debug('AllDays'+ allDays);
14

The addDays method does not modify the value but instead returns the modified date. So you need:

currentDay = currentDay.addDays(1);

Your current code hits the CPU limit because currentDay never changes.

  • Ahhhh, yes now I see my mistake. Thanks! Haven't coded anything in months so rusty :( – Matt M Mar 19 '18 at 16:18

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.