views:

34

answers:

2

Hi,

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

A: 

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];
Benoît
I saw that example, but how can I use it for my problem? I did try a lot with NSDateComponents, but it didn't return the right solution like above. I need an NSMutableArray with the NSDates (same weekday) between two dates. I don't understand really how to use components. I continue trying. Thank you.
FFraenz
I have change my anwer...
Benoît
Benoît: This assumes seven days per week.
Peter Hosey
You don't have seven days per week in US ? ;) (change by using NSDateComponents for week offset)
Benoît
A: 

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.

Peter Hosey
I've done it, Thank you.
FFraenz