1

我有一个使用 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]];
    }
4

2 回答 2

5

您不需要使用 dateFormatter。

if([dateInQuestion compare:newCurrentDate] == NSOrderedAscending && [dateInQuestion compare:sevenDaysBeforeCurrent] == NSOrderedDescending){
    // do something
}
于 2013-02-22T22:33:06.490 回答
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 的一个实例。

于 2013-02-22T22:13:09.127 回答