Question

I want to check to 2 NSDates that they are on the same date (time can be different). What I have currently is this:

- (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];
}
Était-ce utile?

La solution

Your startDate, endDate calculation looks almost correct, you only forgot the NSDayCalendarUnit:

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

There are various ways to compute the start and end date for the current day, I prefer the following slightly shorter code:

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

Your predicate will find all objects that have any note with date >= startDate, and any (possibly different) note with date < endDate.

If you want to find objects that have at least one note on the given day, you need a SUBQUERY:

[NSPredicate predicateWithFormat:@"SUBQUERY(notes, $n, $n.date >= %@ AND $n.date < %@).@count > 0",
           startDate,endDate];
Licencié sous: CC-BY-SA avec attribution
Non affilié à StackOverflow
scroll top