Starting November 20, the site will be set to read-only. On December 4, 2023,
forum discussions will move to the Trailblazer Community.
ShowAll Questionssorted byDate Posted
Yeyeric

# Loop for each month in date range

Hello,

I'm a beginner in APEX and looking to do a basic loop.

Here is my situation. I have 2 fields, start date and end date

I want to do a loop for each month of the period between start and end date.
If more details are needed, start and end date are always 1st of month as per my criteria, and I need to do a basic calculation but I'm stuck with the setting of the loop.

How would you suggest to do this ?

I've been trying to think of something but I can't figure out

Thanks a lot
Balaji Chowdary Garapati
How about some thing like this:

for(integer i=0;i<startdate.monthsBetween(endate);i++){

// put your logic here.
}

Hope this helps

Thanks,
Balaji
Charlotte Gibson 10

In case anyone else lands on this page after doing a similar search to me - I had a requirement similar to this, but it was causing a problem if the start date was in July 2018 and the end date was in Oct 2019 - it would only iterate through the months July to October, and ignore the beginning of 2019.

I've update the logic a bit, as I also had the need to do something with the date I was iterating through - ie adding it in text form to a list:

date startDate = system.today();
date endDate = system.today().addmonths(18);

list<string> thesemonths = new list<string>{};

for(date d=startDate; d <= endDate; d=d.addMonths(1)){
string thisMonth = monthMap.get(d.month()) +  ' ' + d.year();