Loop between two NSDates in lens C

advertisements

I have two dates StartDate and EndDate. I want to find specific days e.g. Monday between these two dates.

How can I execute a loop between two dates?


There are really two parts to this question:

  • how turn a date into a monday
  • how to loop between dates adding a week every time.

Making a date into a monday

You can use NSCalendar to get a monday. In the code below I use the current calendar and change the first day of the week to monday and then make the date the "beginning of the week". It's a trick that I picked up from this answer.

NSDate *loopDate = // the start date you are looping from
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
currentCalendar.firstWeekday = 2; // Monday
[currentCalendar rangeOfUnit:NSWeekCalendarUnit startDate:&loopDate interval:NULL forDate:loopDate];

when I run it right now (my loop date is 3 months ago) it changes Friday, May 17, 2013 at 5:57:26 PM GMT+2 into Monday, May 13, 2013 at 12:00:00 AM GMT+2 (which is the monday before that).

Looping by adding one week

This is really simple. Create date components for "one week" and add it to the date as long as it's smaller than the end date.

NSDateComponents *oneWeek = [NSDateComponents new];
oneWeek.week = 1;

while ([loopDate compare:endDate] == NSOrderedAscending) {
    loopDate = [currentCalendar dateByAddingComponents:oneWeek toDate:loopDate options:0];
    // Do something with the date
}

When I ran this code and logged the dates I got:

Monday, May 20, 2013 at 12:00:00 AM GMT+2
Monday, May 27, 2013 at 12:00:00 AM GMT+2
Monday, June 3, 2013 at 12:00:00 AM GMT+2
Monday, June 10, 2013 at 12:00:00 AM GMT+2
Monday, June 17, 2013 at 12:00:00 AM GMT+2
Monday, June 24, 2013 at 12:00:00 AM GMT+2
Monday, July 1, 2013 at 12:00:00 AM GMT+2
Monday, July 8, 2013 at 12:00:00 AM GMT+2
Monday, July 15, 2013 at 12:00:00 AM GMT+2
Monday, July 22, 2013 at 12:00:00 AM GMT+2
Monday, July 29, 2013 at 12:00:00 AM GMT+2
Monday, August 5, 2013 at 12:00:00 AM GMT+2
Monday, August 12, 2013 at 12:00:00 AM GMT+2
Monday, August 19, 2013 at 12:00:00 AM GMT+2