2

I have three things getting passed to a method that return List

1.Start date eg 1/1/2018

2.End date eg 1/8/2018

3.Days interval eg 7 days

i want to get all the dates from start date to end date based on the days interval.

3 Answers 3

1

It looks like you are trying to find the 7th day after your initial date until you finally come to the end date. Am I right? If so, please see the following code. A while loop will allow you to iterate through your dates and will not go any further than the last date.

Date startDate = date.parse('1/1/2018');
Date endDate = startDate.addMonths(7);

Set<Date> datesBetweenStartEnd = new Set<Date>();

while(startDate < endDate) {
    datesBetweenStartEnd.add(startDate.addDays(7));
    startDate = startDate.addDays(7);
}

System.Debug(datesBetweenStartEnd);

I'm not sure what you want to do with these dates therefore I am just storing them in a set to prevent duplicates (should never be) and so we can see them on the debug log.

Hope this helps.

1

You can do something like below. You can use addDays method of Date class to iterate over Interval days.

Date startDate = System.Today();
Integer interval = 7;
for(Integer i=1; i<=7;i++){
    Date newDate = startDate.addDays(1);
    System.debug('###'+newDate);
    startDate = newDate;
}
1
  • thank you @Devendra i am new to it so i was just looking for logic about how can i iterate a loop till the last date. i am having problem in it. Oct 24, 2016 at 7:33
0

Here is small example of iterating dates in loop. to implement your interval logic add variable and use break keyword.

date d1= system.today();
date d2 = d1.addDays(5);
date temp = d1;
while(temp<d2) {
    system.debug(temp);
    temp = temp.addDays(1);
} 

You must log in to answer this question.

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