NSPredicate用于检查同一日期

时间:2013-10-16 15:46:35

标签: objective-c ios7 nsdate nspredicate nsdatecomponents

我想检查2 NSDate他们是否在同一天(时间可能不同)。 我现在的目的是:

- (NSPredicate*) predicateWithDate:(NSDate *)date {
    NSCalendar *calendar = [NSCalendar currentCalendar];
    NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit ) fromDate:date];
    //create a date with these components
    NSDate *startDate = [calendar dateFromComponents:components];
    [components setMonth:0];
    [components setDay:1];
    [components setYear:0];
    NSDate *endDate = [calendar dateByAddingComponents:components toDate:startDate options:0];
    return [NSPredicate predicateWithFormat:@"((ANY notes.date >= %@) AND (ANY notes.date < %@))",startDate,endDate];
}

1 个答案:

答案 0 :(得分:1)

你的startDate,endDate计算看起来几乎正确,你只忘了NSDayCalendarUnit

NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:date];

有多种方法可以计算当天的开始和结束日期, 我更喜欢以下略短的代码:

NSCalendar *calendar = [NSCalendar currentCalendar];
NSDate *startDate;
NSTimeInterval interval;
[calendar rangeOfUnit:NSDayCalendarUnit startDate:&startDate interval:&interval forDate:date];
NSDate *endDate = [startDate dateByAddingTimeInterval:interval];

您的谓词会找到所有带有date >= startDate注释的对象, 以及date < endDate的任何(可能是不同的)音符。

如果要查找在给定日期至少有一个音符的对象,则需要提示:

[NSPredicate predicateWithFormat:@"SUBQUERY(notes, $n, $n.date >= %@ AND $n.date < %@).@count > 0",
           startDate,endDate];