0

我想检查到 2NSDate秒,它们是否在同一日期(时间可以不同)。我目前拥有的是这样的:

- (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];
}
4

1 回答 1

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

如果要查找在给定日期至少有一个注释的对象,则需要一个 SUBQUERY:

[NSPredicate predicateWithFormat:@"SUBQUERY(notes, $n, $n.date >= %@ AND $n.date < %@).@count > 0",
           startDate,endDate];
于 2013-10-16T16:00:10.307 回答