简体   繁体   中英

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

In my app I have an NSMutableArray that users can modify by adding or deleting entries from the array (btw entries are always added at index 0), this is done using a table view. Each entry in the array store's the date that the cell was added on as an NSString is this format: ie @"Sat, Mar 12, 2011" . Let's say that I also create a variable NSString *myDay = @"Thu";

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

Also note that in my app, the variable myDay is not a specific date (ie @"Thu, Mar 10, 2011" it just represents a day of the week chosen by the user, were some data in my app will need to be reset every week.

NSDateComponents and NSCalendar let you do this kind of logic on NSDates.

If you have dates modeled in your app as strings, you will need to convert them to NSDates first. Better would be to model your dates as NSDates and use a formatter to turn them into strings for display in the table.

You can put the dates into an array and sort this array. Than you check, if the index of these different dates, to see, if one date lies 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];

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM