一尘不染

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

swift

我对此有疑问,因此没有找到正确的答案,因此在这里我将留下一个小教程。

目标是按今天的日期过滤获取的对象。

注意:它与Swift 3兼容。


阅读 220

收藏
2020-07-07

共1个答案

一尘不染

您不能简单地将您的日期与今天的日期进行比较:

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: "%@ < %@", date as NSDate, dateTo as NSDate)
let datePredicate = NSCompoundPredicate(andPredicateWithSubpredicates: [fromPredicate, toPredicate])
fetchRequest.predicate = datePredicate

到目前为止,这是仅显示具有当前日期的对象的最简单,最短的方法。

2020-07-07