如何检查NSDate是否落在NSMutableArray中的其他两个NSDate之间 [英] How can I check if an NSDate falls in between two other NSDates in an NSMutableArray

查看:91
本文介绍了如何检查NSDate是否落在NSMutableArray中的其他两个NSDate之间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

在我的应用程序中,我有一个NSMutableArray,用户可以通过从数组中添加或删除条目(btw条目总是添加在索引0)修改,这是使用表视图。数组存储中每个条目的单元格作为NSString添加的日期是这种格式: @2011年3月12日星期六。让我们说我还创建一个变量 NSString * myDay = @Thu;

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: i.e. @"Sat, Mar 12, 2011". Let's say that I also create a variable NSString *myDay = @"Thu";

我检查在索引0存储的日期和索引1存储的日期之间,由myDay表示的日缺失或不在这两个日期之间。在我的例子中,我只需要通过比较数组的索引0和1来做这个检查。

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.

还要注意,在我的应用程序中,变量myDay不是特定日期(即@Thu,2011年3月10日),它只代表用户选择的一周中的某一天,我的应用中的某些数据需要每周重置。

Also note that in my app, the variable myDay is not a specific date (i.e @"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.

推荐答案

你可以把日期放入一个数组并排序这个数组。比起你检查,如果这些不同的日期的索引,看,如果一个日期位于其他:

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

这篇关于如何检查NSDate是否落在NSMutableArray中的其他两个NSDate之间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆