How can I check if NSDate falls between two other NSDates in NSMutableArray

In my application, I have an NSMutableArray that users can modify by adding or removing entries from the array (btw entries are always added to index 0), this is done using a table view. Each record in the array stores the date when the cell was added as an NSString - this is the format: i.e. @"Sat, Mar 12, 2011". Let's say that I also create a variableNSString *myDay = @"Thu";

My question is: how can I check that between the date stored at index 0 and the date stored at index 1, the day represented by myDay is missing or does not lie between the two dates. And in my case, I only need to do this check by comparing the indexes 0 and 1 of the array.

Also note that in my application the variable myDay is not a specific date (ie @ "Thu, March 10, 2011", it represents only the day of the week selected by the user, there was some data in my application. Reset every week.

0
source share
2 answers

You can put dates in an array and sort this array. If you check if the pointer of these different dates, to see if one date is between the others:

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];

NSDateComponents *comps1 = [[NSDateComponents alloc] init];
NSDateComponents *comps2 = [[NSDateComponents alloc] init];
NSDateComponents *comps3 = [[NSDateComponents alloc] init];

[comps1 setDay:10];
[comps2 setDay:12];
[comps3 setDay:11];

NSDate *day1 = [gregorian dateByAddingComponents:comps1 toDate:[NSDate date] options:0];
NSDate *day2 = [gregorian dateByAddingComponents:comps2 toDate:[NSDate date] options:0];
NSDate *day3 = [gregorian dateByAddingComponents:comps3 toDate:[NSDate date] options:0];

NSMutableArray *array = [NSMutableArray arrayWithObjects:day1, day2, day3, nil];


[array sortUsingSelector:@selector(compare:)];

NSUInteger indexOfDay1 = [array indexOfObject:day1];
NSUInteger indexOfDay2 = [array indexOfObject:day2];
NSUInteger indexOfDay3 = [array indexOfObject:day3];

if (((indexOfDay1 < indexOfDay2 ) && (indexOfDay2 < indexOfDay3)) || 
    ((indexOfDay1 > indexOfDay2 ) && (indexOfDay2 > indexOfDay3))) {
    NSLog(@"YES");
} else {
    NSLog(@"NO");
}



[comps1 release];
[comps2 release];
[comps3 release];
[gregorian release];
+1
source

NSDateComponents and NSCalendar allow you to do this logic in NSDates.

, , NSDates. NSDates , .

+3

All Articles