joostevilghost
joostevilghost

Reputation: 149

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?

Upvotes: 5

Views: 2899

Answers (3)

Жека Yarotski
Жека Yarotski

Reputation: 11

From Apple doc: To compute a sequence of dates, use the enumerateDatesStartingAfterDate:matchingComponents:options:usingBlock: method instead of calling this method ( - nextDateAfterDate:matchingComponents:options: ) in a loop with the previous loop iteration's result.

As I got, it will iterate all dates that matched with "matchingComponents" till you finish iteration with "stop.memory = true"

let calendar = NSCalendar.currentCalendar()
let startDate = calendar.startOfDayForDate(NSDate())
let finishDate = calendar.dateByAddingUnit(.Day, value: 10, toDate: startDate, options: [])
let dayComponent = NSDateComponents()
dayComponent.hour = 1

calendar.enumerateDatesStartingAfterDate(startDate, matchingComponents: dayComponent, options: [.MatchStrictly]) { (date, exactMatch, stop) in
    print(date)
    if date!.compare(finishDate!) == NSComparisonResult.OrderedDescending {
        // .memory gets at the value of an UnsafeMutablePointer
        stop.memory = true
    }
}

Upvotes: 0

gaige
gaige

Reputation: 17481

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];        

Upvotes: 7

edc1591
edc1591

Reputation: 10182

Just create them and add them to an array...

NSMutableArray *arr = [NSMutableArray array];
NSDateComponents *comps = [[[NSDateComponents alloc] init] autorelease];
[comps setMonth:1];
[comps setYear:2012];

for(int i=1;i<=7;i++) {
    [comps setDay:i];
    [arr addObject:[[NSCalendar currentCalendar] dateFromComponents:comps]];
}

Upvotes: 1

Related Questions