我正在尝试过滤对象数组,选择 NSDate 类型的属性等于特定日期的对象。但是,我只想比较日期并忽略任何时间差异。
所以我这样使用 NSPredicate:
NSPredicate *predicate = [NSPredicate predicateWithFormat:@"PropertyWithDate == %@",
[NSDate date]];
由于该对象存储了日期和时间,并且现在我传递的值同时保存了两者。如何安排它在比较过程中忽略两者的时间部分?
最佳答案
请记住,NSDate 表示时间点,与时区无关,因此只有相对于特定日历和时区讨论 NSDate 的日期部分才有意义。
简单的回答是,您需要构造两个 NSDate:一个用于日期当天的上午 12 点,另一个用于日期后一天的上午 12 点,然后设置谓词来查找两者之间的日期:
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"PropertyWithDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"PropertyWithDate < %@", secondDate];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubPredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];
要构造 firstDate
和 secondDate
,您需要使用 NSCalendar
的 components:fromDate:
和 dateFromComponents:
方法。如果您想使用设备当前的默认日历和时区,只需使用[NSCalendar calendar]
即可获取要使用的日历。
关于Objective-C - 如何查找 prop 等于日期的对象?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/9604127/