Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 246
joostevilghost Avatar asked Mar 10 '12 23:03

joostevilghost


People also ask

How do you create a date range in pandas?

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).


2 Answers

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];        
like image 140
gaige Avatar answered Sep 30 '22 12:09

gaige


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]];
}
like image 42
edc1591 Avatar answered Sep 30 '22 11:09

edc1591