Question

I have following problem: I need to create an NSMutabeArray with every weekday after a specific date.

This should look like:

  • Thursday 28 october 2010
  • Thursday 04 october 2010
  • Thursday 11 october 2010
  • ...

How can I do that? I think it has something to do with NSCalendar, but I can't find the right solution... Could you help me?

Thank you in advance

FFraenz

Was it helpful?

Solution

That's an infinite series; an NSMutableArray can only hold a finite collection.

At any rate, you need only a single member of the series, such as 2010-10-28. To get the Thursday after that, add one week. To get the third date in the series, add a week to the second date, or two weeks to the first date. Having any member of the series provides you with access to any other member of the series.

If you are starting from a date that isn't the right weekday, get the date components for that date, add the difference between the correct weekday and the weekday it has to its day of the month, and convert the amended date components back to a date. That date will then be on the desired weekday in the same week.

OTHER TIPS

To have actual date:

NSDate *today = [[NSDate alloc] init];

To add a week:

NSDate *nextDate = [today dateByAddingTimeInterval:60*60*24*7];

Then you can iterate and create your array:

NSMutableArray* dates = [[NSMutableArray alloc] init];
NSDate *date= [[NSDate alloc] init];

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
NSDateComponents *offsetComponents = [[NSDateComponents alloc] init];
[offsetComponents setWeek:1];

for (int i=0;i<10;i++) {
  NSDate *nextDate = [gregorian dateByAddingComponents:offsetComponents toDate:date options:0];
  [dates addObject:date];
  [date release];
  date = nextDate;
}
[date release];
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top