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?
Specifying the valuesSpecify start and end , with the default daily frequency. Specify start and periods , the number of periods (days). Specify end and periods , the number of periods (days). Specify start , end , and periods ; the frequency is generated automatically (linearly spaced).
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];
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]];
}
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With