1

I have a function having 3 input startdate, dayofmonth and monthcount. I want to store all the dates in a List<Date> which start from startdate and after every given monthcount add the dayofmonth date in the Date list.

Example I have dayofmonth=2 and monthcount=3 and start date as 5th feb 2016 then I need 50 next Dates stored in the list after every 3 months on the 2nd day of the month. below is my code and any help in the logic would be aprreciated

public Date calculateEndDateWhenMontlhy(String dayOfTheMonth, Integer monthCount, Date starDate) {
     List<Date> monthlyDates = new List<Date>();
     Integer day = Integer.valueOf(dayOfTheMonth);
     System.debug(day);
 }

2 Answers 2

3

Using your code, a simple answer for adding the next 50 dates would be this:

Date baseDate = date.newInstance(startDate.year(), startDate.month(), 1);

for(Integer i = 0; i < 50; i++){
    monthlyDates.add(baseDate.addMonths(monthCount));
    baseDate = baseDate.addMonths(monthCount);
}

This will need a bit of tweaking to ensure the values passed in are correct, and that the numbers are within reasonable ranges for the month given.

1

For next 50 dates, you need to iterate 50 times using a for loop and do your logic of adding dates inside it. The following code will guide you to get you up to speed.

public List<Date> calculateEndDateWhenMontlhy(String dayOfTheMonth, Integer monthCount, Date starDate) {
    List<Date> monthlyDates = new List<Date>();
    Date startDate = Date.newInstance(starDate.year(), starDate.month(), Integer.valueOf(dayOfTheMonth));
    monthlyDates.add(startDate);
    system.debug(startDate);
    for(Integer i=1; i<50; i++){
        Date d = startDate.addmonths(monthCount*i);
        system.debug(d);
        monthlyDates.add(d);
        //monthlDates.add(startDate.addmonths(monthCount*i)); // Previous 2 lines can be combined to this single line
    }
    return monthlyDates;
}

Hope it helps.

You must log in to answer this question.

Not the answer you're looking for? Browse other questions tagged .