检查date是否在范围之间

我有一个使用UICollectionView的自定义日历设置,我有一个数组,可以保存30天的date。 我想要做的是找出一个值是否在当前date和之前的7天之间。 如果是我需要它做一些事情。 我无法弄清楚我做错了什么。 这是我到目前为止:

NSDateFormatter *df = [NSDateFormatter new]; [df setDateFormat:@"MM-dd-yy"]; NSdate *date = [NSDate date]; NSDate *newCurrentDate = [date dateByAddingTimeInterval:+14*24*60*60]; NSDate *sevenDaysBeforeCurrent = [date dateByAddingTimeInterval:-7*24*60*60]; if([[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:newCurrentDate]] == NSOrderedAscending && [[df stringFromDate:[days objectAtIndex:indexPath.item]] compare:[df stringFromDate:sevenDaysBeforeCurrent]] == NSOrderedDescending ) { UIImage *buttonImage = [UIImage imageNamed:@"dates.png"]; [myButton setBackgroundImage:buttonImage forState:UIControlStateNormal]; } 

它所做的是改变newCurrentDate之前的每一个date的形象,而不是前面的7.任何人都可以看到我在做什么错了?

下面是数组的初始化:

 myDays = [[NSMutableArray alloc] init]; NSCalendar *cal = [NSCalendar autoupdatingCurrentCalendar]; NSDate *today = [NSDate date]; date = [NSDate date]; for (int i = 0; i < 31; i++) { NSDateComponents *comps = [[NSDateComponents alloc]init]; [comps setDay:i]; [myDays addObject:[cal dateByAddingComponents:comps toDate:today options:0]]; } 

尝试一下这些方面:

 NSDate *currentDate = [NSDate date]; NSDate *dateSevenDaysPrior = [currentDate dateByAddingTimeInterval:-(7 * 24 * 60 * 60)]; NSDate *someDate = [currentDate dateByAddingTimeInterval:-(3 * 24 * 60 * 60)]; // adjust as you like if (([dateSevenDaysPrior compare:someDate] != NSOrderedDescending) && ([someDate compare:currentDate] != NSOrderedDescending)) { NSLog(@"date is in range"); } else { NSLog(@"date is not in range"); } 

这假定你提供的东西( someDate在这个例子中代表什么)实际上是NSDate的一个实例。

你不需要使用dateFormatter。

 if([dateInQuestion compare:newCurrentDate] == NSOrderedAscending && [dateInQuestion compare:sevenDaysBeforeCurrent] == NSOrderedDescending){ // do something }