Iphone 如何判断特定NSDate(来自NSMutableArray中的NSDate列表)是否属于不同的一周?

Iphone 如何判断特定NSDate(来自NSMutableArray中的NSDate列表)是否属于不同的一周?,iphone,objective-c,cocoa-touch,Iphone,Objective C,Cocoa Touch,基本上,我想知道用户从我的设置中选择一周的开始日期(这将有一个格式的值,例如@“Mon”),我有一个NSMutableArray,它以时间升序的方式保存NSDates(用户在应用程序的整个生命周期中添加这些日期),但不一定是连续的(用户可能错过了某一天,并且没有将日期添加到数组中),我如何确定数组中的某个特定日期是另一周的一部分(相对于用户选择的开始一周的日期)?使用NSDateComponents。您可以使用NSCalendar实例从日期获取它们。这将在几周内为您提供两个日期之间的差异: NS

基本上,我想知道用户从我的设置中选择一周的开始日期(这将有一个格式的值,例如@“Mon”),我有一个NSMutableArray,它以时间升序的方式保存NSDates(用户在应用程序的整个生命周期中添加这些日期),但不一定是连续的(用户可能错过了某一天,并且没有将日期添加到数组中),我如何确定数组中的某个特定日期是另一周的一部分(相对于用户选择的开始一周的日期)?

使用
NSDateComponents
。您可以使用
NSCalendar
实例从日期获取它们。

这将在几周内为您提供两个日期之间的差异:

NSDateComponents *dateDifference = [gregorian components:NSWeekCalendarUnit fromDate:day1 toDate:day2 options:0];
NSUInteger weeksDiff = [dateDifference week];
所以
if(!weekDiff){/*同一周*/}

完整示例:

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

NSDateComponents *comps1 = [[NSDateComponents alloc] init];
NSDateComponents *comps2 = [[NSDateComponents alloc] init];
[comps1 setDay:5];
[comps2 setDay:12];

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


NSDateComponents *dateDifference = [gregorian components:NSWeekCalendarUnit fromDate:day1 toDate:day2 options:0];

NSLog(@"\n%@ \n%@\n%d", day1, day2, [dateDifference week]);
[comps1 release];
[comps2 release];
[gregorian release];
有关将字符串转换为NSDATE的信息,请参见

编辑作为对评论的回应
如果你想有一个从你第一次进入的日期开始的一周,你可以改为数数天数,并检查它们是否有超过7天的差异

NSDateComponents *dateDifference = [gregorian components:NSDayCalendarUnit fromDate:day1 toDate:day2 options:0];
NSUInteger daysDiff = [dateDifference day];
if(weekDiff < 7){ /*same week*/}
NSDateComponents*dateDifference=[gregorian components:NSDayCalendarUnit fromDate:day1 toDate:day2选项:0];
NSU整数daysDiff=[dateDifference day];
如果(工作日间隔<7){/*同一周*/}

您已经三次询问了这个问题的细微变化(这个问题,我已经回答了)。您确定在得到可接受的答案之前修改其中一个问题不是更好吗?如果您继续删除并重新提问,您的帐户将被暂停。仅供参考。您已经得到了(一个)这个网站的创始人。这真的不是很有趣。我如何调整它,使一周的开始日不是默认的。假设我想这样做相对于星期三是一周的开始?