NSPredicate for range between two dates is not working as expected

て烟熏妆下的殇ゞ 提交于 2019-11-29 11:14:06

NSDate objects include the time as well. When you pass a date with no time to the dateFromString: method, the midnight of the corresponding day is assumed, i.e. only the items that happen on midnight would return true in the less than or equal expression.

There are two common ways of solving it:

  • Add one day to rangeEnd, and use "less than" instead of "less than or equal", or
  • Add the time to the rangeEnd date (this is not ideal, because you would either need to specify the time in a long string, or miss the items that happened on the last second of the day).

Here is how to use the first approach:

request.predicate = [NSPredicate
    predicateWithFormat:@"createdDate >= %@ AND createdDate < %@"
    , rangeStart
    , [rangeEnd dateByAddingTimeInterval:60*60*24]
];

Remember that even though the name of the class is NSDate, these objects represent specific points in time (not an entire day). rangeEnd is set to midnight of October 4th. Since midnight is the first instant of that day, only events at midnight of that day will be included in your results. Move rangeEnd to the next day as shown below and you should get the results you expect.

NSCalendar* calendar = [NSCalendar autoupdatingCurrentCalendar];
NSDateComponents* components = [[NSDateComponents alloc] init];
components.day = 1;
NSDate* newDate = [calendar dateByAddingComponents:components toDate:rangeEnd options: 0];
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!