目标是在今天的日期过滤提取的对象.
注意:它与Swift 3兼容.
您不能简单地使用您的日期与今天的日期进行比较:let today = Date()let datePredicate = nspredicate(format: "%K == %@",#keyPath(ModelType.date),today)
它不会显示任何内容,因为您的日期不太可能是完全比较日期(它还包括秒和毫秒)
解决方案是这样的:
// Get the current calendar with local time zonevar calendar = Calendar.currentcalendar.timeZone = NSTimeZone.local// Get today's beginning & endlet dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00let dateto = calendar.date(byAdding: .day,value: 1,to: dateFrom)// Note: Times are printed in UTC. Depending on where you live it won't print 00:00:00 but it will work with UTC times which can be converted to local time// Set predicate as date being today's datelet fromPredicate = nspredicate(format: "%@ >= %@",date as NSDate,dateFrom as NSDate)let topredicate = nspredicate(format: "%@ < %@",dateto as NSDate)let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate,topredicate])fetchRequest.predicate = datePredicate
这是迄今为止最简单的&只显示具有今天日期的对象的最短方式.
总结以上是内存溢出为你收集整理的swift – 核心数据谓词按今天的日期过滤全部内容,希望文章能够帮你解决swift – 核心数据谓词按今天的日期过滤所遇到的程序开发问题。
如果觉得内存溢出网站内容还不错,欢迎将内存溢出网站推荐给程序员好友。
欢迎分享,转载请注明来源:内存溢出
评论列表(0条)