我使用 Core Data 来存储我的数据模型对象。每个对象都有 NSDate 属性。
NSDate 属性的格式如下:
2013-03-18 12:50:31 +0000
我需要创建谓词,仅通过此值 2013-03-18
立即获取我的对象。
最佳答案
如果您的日期存储为实际日期,那么您应该利用它来发挥自己的优势,而不是摆弄格式。您可以简单地创建一个谓词来检查日期是否在两个日期(带时间)之间。第一个日期是您的日期,时间为 00:00:00,第二个日期是在那之后的一天。
// 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]];
关于ios - NSPredicate 按年月日过滤,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/15500166/