ios - NSPredicate 按年月日过滤

标签 ios date core-data nspredicate

我使用 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/

相关文章:

ios - 登录后Swift Facebook SDK空白页面

ios - 路径中的线呈 180 度时出现意外的 LineJoinStyle 行为

php收集两个日期之间的日期并为每个日期创建条目

php - 从 HTML5 表单获取日期 - 并发布到 MySQL

core-data - 将 NSArray 转换为 Swift Array<T>

iphone - 如何将此数组加载到核心数据实体中?

c# - 在 Xamarin 表单中获取正确的设备宽度

ios - shouldInteractWith url textview 委托(delegate)未在 ios9 中调用但在 ios10 中工作?

bash - 在bash脚本中减去两个时间戳

ios - 核心数据 ANY ANY 多 INNER JOIN