检查日期是否在范围之间

时间:2013-02-22 21:49:19

标签: ios objective-c

我有一个使用UICollectionView的自定义日历设置,我有一个数组,可以保存30天的日期。我想要做的是找出一个值是否在当前日期和它之前的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之前的每个日期的图像,而不是之前的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]];
    }

2 个答案:

答案 0 :(得分:5)

您不需要使用dateFormatter。

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

答案 1 :(得分:1)

尝试以下几点:

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的一个实例。