Search code examples
iosobjective-cnsdatenscalendar

Find all days of a week/month/year and add to NSMutableArray


I have an NSMutableArray, and i want to be able to pull out only the rows that are in a cetain time frame such as each week or month or year. I can get a date thats a week back so i would have the current date and the date a week back, but i need to be able to grab all those days then add them to an array so i can search through them.

This is how i am grabbing the day and the day a week back.

-(void)getCalDays {
cal = [NSCalendar currentCalendar];

NSDate *date = [NSDate date];
NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:date];
today = [cal dateFromComponents:comps];


   NSLog(@"today is %@", today);
    [self getWeek];
}

-(void)getWeek {
    NSDateComponents *components = [[NSDateComponents alloc] init];
    [components setDay:-6];
    weekDate = [cal dateByAddingComponents:components toDate:today options:0];
    NSLog(@"Week of %@ THRU %@", today, weekDate);
}

So how can i find all the days in between the two dates and load them into an array?


Solution

  • You're on your way. The key is to advance the component's day in a loop and extract a date from them.

    NSMutableArray *result = [NSMutableArray array];
    NSCalendar *cal = [NSCalendar currentCalendar];
    
    NSDate *startDate = // your input start date
    NSDate *endDate = // your input end date
    
    NSDateComponents *comps = [cal components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit)fromDate:startDate];
    NSDate *date = [cal dateFromComponents:comps];
    
    while (![date isEqualToDate:endDate]) {
        [result addObject:date];
        [comps setDay:(comps.day + 1)];
        date = [cal dateFromComponents:comps];
    }
    

    Note that this will result in a collection of dates inclusive of the first date, exclusive of the last date. You can probably work out on your own how to change the edge conditions.