Get an array of future NSDates

I have a date picker.

After choosing the time from this, I would like to get the dates of the next 64 Mondays.

How do I start writing a method to accept a date and return an NSArray from NSDates within the next 64 Mondays from that date.

eg. I selected the time at 6:45 pm from the date picker, then I want to get the next 64 Mondays with the set time.

+7
source share
3 answers

Example (ARC):

NSDate *pickerDate = [NSDate date]; NSLog(@"pickerDate: %@", pickerDate); NSDateComponents *dateComponents; NSCalendar *calendar = [NSCalendar currentCalendar]; dateComponents = [calendar components:NSWeekdayCalendarUnit fromDate:pickerDate]; NSInteger firstMondayOrdinal = 9 - [dateComponents weekday]; dateComponents = [[NSDateComponents alloc] init]; [dateComponents setDay:firstMondayOrdinal]; NSDate *firstMondayDate = [calendar dateByAddingComponents:dateComponents toDate:pickerDate options:0]; dateComponents = [[NSDateComponents alloc] init]; [dateComponents setWeek:1]; for (int i=0; i<64; i++) { [dateComponents setWeek:i]; NSDate *mondayDate = [calendar dateByAddingComponents:dateComponents toDate:firstMondayDate options:0]; NSLog(@"week#: %i, mondayDate: %@", i, mondayDate); } 

NSLog Output:
picker Date: 2011-12-09 20:38:25 +0000
Week No: 0, Monday: 2011-12-12 20:38:25 +0000
Week No: 1, Monday: 2011-12-19 20:38:25 +0000
Week No: 2, Monday: 2011-12-26 20:38:25 +0000
Week No: 3, Monday: 2012-01-02 20:38:25 +0000
- the remaining 60 are here -

+3
source

Start with the NSDate from the collector and continue to add 24 * 60 * 60 seconds to it until Monday appears. Add the total date to the result. Continue to add 7 * 24 * 60 * 60 seconds until the last date you added, and click on the result of the returned list until you get all 64 Mondays. Here's how you find out if NSDate on Monday:

 NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar]; NSDateComponents *weekdayComponents =[gregorian components:NSWeekdayCalendarUnit fromDate:dateOfInterest]; NSInteger weekday = [weekdayComponents weekday]; if (weekday == 2) ... // 2 represents Monday 

EDIT: DaveDeLong pointed out the drawback of the above algorithm: it will shift the time twice during the daylight saving time. Instead of counting seconds manually, use this code to add a day to NSDate :

 NSDate *currentDate = [NSDate date]; NSDateComponents *comps = [[NSDateComponents alloc] init]; [comps setDay:1]; // Add 1 when searching for the next Monday; add 7 when iterating 63 times NSDate *date = [gregorian dateByAddingComponents:comps toDate:currentDate options:0]; [comps release]; 
+2
source

You can use NSCalendar to determine which day of the week is today (at a selected time); toss it to get to the next Monday, and then lift it up 7 days 63 times to get the Mondays that seem to you.

+1
source

All Articles