NSPredicate按年蛾日过滤

Mat*_*der 9 date core-data nspredicate ios

我使用Core Data来存储我的数据模型对象.每个对象都有NSDate属性.

NSDate属性的格式如下:

2013-03-18 12:50:31 +0000
Run Code Online (Sandbox Code Playgroud)

我需要创建谓词,这个谓词只是通过这个值来获取我的对象2013-03-18而没有时间.

Dav*_*ist 11

如果您的日期存储为实际日期,那么您应该使用它而不是格式化.您可以简单地创建一个谓词,检查日期是否在两个日期之间(有时间).第一个日期是您的日期,时间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]];
Run Code Online (Sandbox Code Playgroud)

  • +1比我更快和*注意1天!= 24小时*评论 (3认同)
  • @ A-Live,是的,我编辑了我在这里发布的代码:http://stackoverflow.com/questions/10954273/how-do-i-do-this-nspredicate-code/10954503#10954503 (2认同)