NSPredicate和CoreData - 在iOS上决定Date属性是“今天”(或在昨晚12点到今晚12点之间)

时间:2012-02-22 19:17:58

标签: core-data nsdate uitableview nspredicate nsfetchedresultscontroller

我正在使用NSFetchedResultsControllerUITableViewController从CoreData数据库填充UITableView。

我有一个NSDate对象保存在标记为“startTime”的Date属性中。然后我试图通过使用看起来像这样的NSPredicate来获取今天的数据:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
                          todaysDate];

我的结果为零。我理解这一点是因为一个NSDate对象只保留了自1970年1月1日以来的秒数或毫秒数等等吗?因此,比较1111111111111和1111111111112,而在同一天,两个不同的NSDate对象不相等。

那么,如何对NSPredicate进行格式化以便它能够实现呢?我猜它会创建两个NSDate对象:一个是昨晚12点,另一个是今晚12点,并比较startDate,看看它是否在这两个NSDate之间。

我是NSPredicate的新手,所以怎么能实现呢?

1 个答案:

答案 0 :(得分:24)

使用NSCompoundPredicate

NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];

firstDate今天早上12点,secondDate今晚12点。

P.S。以下是今天早上12点的结果:

NSCalendar *calendar = [NSCalendar calendar]; // gets default calendar
NSCalendarComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, and day for today's date
NSDate *firstDate = [calendar dateFromComponents:components]; // makes a new NSDate keeping only the year, month, and day

今晚12点,请更改components.day