Core Data Predicate Date Comparison

前端 未结 5 2124
醉话见心
醉话见心 2020-12-01 04:50

Im trying to fetch all the objects in an entity matching a user selectedDate (it\'s an NSDate). The Core Data code is fine but my predicate keeps returning 0 results, the da

5条回答
  •  [愿得一人]
    2020-12-01 05:14

    While in human communication date often is equal with day, it is not the same with NSDate objects: A NSDate represents a single moment in time. Dates that are different just in seconds aren't equal. And actually they dont represent days, month, year at all, as this is different from calendar system to calendar system

    you must define for yourself if dates in the same minute, hour, day … are equal. So basically you must teach the program to allow some fuzziness.

    here for minute resolution

    NSDate *startDate = ....;
    NSTimeInterval length;
    
    [[NSCalendar currentCalendar] rangeOfUnit:NSMinuteCalendarUnit 
                                    startDate:&startDate
                                     interval:&length 
                                      forDate:startDate];
    
    NSDate *endDate = [startDate dateByAddingTimeInterval:length];
    
    NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(eDate >= %@) AND (eDate < %@)", startDate, endDate];
    

    For dates on the same day (aware of Timezones and Daylight Saving Times) you just would change this:

    [[NSCalendar currentCalendar] rangeOfUnit:NSDayCalendarUnit 
                                    startDate:&startDate
                                     interval:&length 
                                      forDate:startDate];
    

提交回复
热议问题