joostevilghost joostevilghost - 5 months ago 18
Objective-C Question

Create a range of dates

I want to create a array of range which contains days betweens a specific start and end date.

For example, I have a start date with 1 January 2012 and and an end date with 7 January 2012. The array or range should contain a collection of NSDate objects (7 in total).

How do I do this?

Answer

NSCalendar is helpful here, since it knows the calendar related to the dates. So, by using the following (assuming you have startDate and endData and that you want to include both in the list), you can iterate through the dates, adding a single day (NSCalendar will take care of wrapping the months and leap year, etc).

NSMutableArray *dateList = [NSMutableArray array];
NSCalendar *currentCalendar = [NSCalendar currentCalendar];
NSDateComponents *comps = [[NSDateComponents alloc] init];
[comps setDay:1];

[dateList addObject: startDate];
NSDate *currentDate = startDate;
// add one the first time through, so that we can use NSOrderedAscending (prevents millisecond infinite loop)
currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate  options:0];
while ( [endDate compare: currentDate] != NSOrderedAscending) {
    [dateList addObject: currentDate];
    currentDate = [currentCalendar dateByAddingComponents:comps toDate:currentDate  options:0];
}

[comps release];