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

Core Data Predicate Filter By Today's Date

如何通过 Swift 中的 Date 属性过滤核心数据管理对象?

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

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

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

这是迄今为止仅显示具有今天日期的对象的最简单和最短的方法。

在 swift4 中,Lawrence413 可以稍微简化一下:

//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)

它去掉了component部分,使代码具有更好的可读性。

在 Lawrence413 的回答中添加以下内容可能会有所帮助:要过滤具有保留今天日期的属性的记录列表,您可以使用:

let fromPredicate = NSPredicate(format: "datetime >= %@", dateFrom as NSDate)
let toPredicate   = NSPredicate(format: "datetime < %@",  dateToUnwrapped as NSDate)

...其中“日期时间是属性的名称”