swift – 核心数据谓词按今天的日期过滤

前端之家收集整理的这篇文章主要介绍了swift – 核心数据谓词按今天的日期过滤前端之家小编觉得挺不错的,现在分享给大家,也给大家做个参考。
我有这方面的问题,我没有找到一个正确的答案所以我会在这里留下一个小教程.

目标是在今天的日期过滤提取的对象.

注意:它与Swift 3兼容.

您不能简单地使用您的日期与今天的日期进行比较:
let today = Date()
let datePredicate = NSPredicate(format: "%K == %@",#keyPath(ModelType.date),today)

它不会显示任何内容,因为您的日期不太可能是完全比较日期(它还包括秒和毫秒)

解决方案是这样的:

// Get the current calendar with local time zone
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local

// Get today's beginning & end
let dateFrom = calendar.startOfDay(for: Date()) // eg. 2016-10-10 00:00:00
let 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 date
let 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相关文章