NSPredicate在年份之前过滤

我使用核心数据来存储我的数据模型对象。 每个对象都有NSDate属性。

NSDate属性的格式如下:

2013-03-18 12:50:31 +0000 

我需要创build一个谓词,它将在没有时间的情况下通过这个值来获取我的对象。

如果你的date存储为实际date,那么你应该使用这个优势,而不是格式化。 您可以简单地创build一个谓词来检查date是否在两个date之间(使用时间)。 第一个date是你的date,时间是00:00:00,第二个date是在那之后的一天。

 // Create your date (without the time) NSDateComponents *yourDate = [NSDateComponents new]; yourDate.calendar = [NSCalendar currentCalendar]; yourDate.year = 2013; yourDate.month = 3; yourDate.day = 18; NSDate *startDate = [yourDate date]; // Add one day to the previous date. Note that 1 day != 24 h NSDateComponents *oneDay = [NSDateComponents new]; oneDay.day = 1; // one day after begin date NSDate *endDate = [[NSCalendar currentCalendar] dateByAddingComponents:oneDay toDate:startDate options:0]; // Predicate for all dates between startDate and endDate NSPredicate *dateThatAreOnThatDay = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date < %@)", startDate, endDate]]; 

虽然大卫显示如何创build一个谓词,我想添加一个更简单的方法来生成一个date为0:00

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

现在, startDate包含一个代表当天时区为0:00的date

 NSDate *endDate = [startDate dateByAddingTimeInterval:lengthDay]; 

现在我们可以把它放入谓词中

 NSPredicate *daySpanPredicate = [NSPredicate predicateWithFormat:@"(date >= %@) AND (date < %@)", startDate, endDate]; 

感谢MartinR的改进。