objective-cnsdatensdatecomponents

How to get future dates using NSDateComponents?


How to get a few future dates with Wednesdays and Fridays using NSDateComponents?


Solution

  • This is actually a bit of a tricky problem if you want it to be totally bullet-proof. Here's how I would do it:

    NSInteger wednesday = 4; // Wed is the 4th day of the week (Sunday is 1)
    NSInteger friday = 6;
    
    NSDate *start = ...; // your starting date
    NSDateComponents *components = [[NSDateComponents alloc] init];
    NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
    
    for (int i = 0; i < 100; ++i) {
      [components setDay:i];
      NSDate *target = [gregorian dateByAddingComponents:components toDate:start options:0];
      NSDateComponents *targetComponents = [gregorian components:NSUIntegerMax fromDate:target];
      if ([targetComponents weekday] == wednesday || [targetComponents weekday] == friday) {
        NSLog(@"found wed/fri on %d-%d-%d", [targetComponents month], [targetComponents day], [targetComponents year]);
      }
    }
    
    [gregorian release];
    [components release];