我该如何用Swift过滤Core Data托管对象的Date
属性?
目标是按照今天的日期过滤获取的对象。
我该如何用Swift过滤Core Data托管对象的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
这是最简单、最快捷的方法,只显示今天日期的对象。
NSPredicate(format: "date == Date()")
实际上会崩溃。 - Martin Rlet fromPredicate = NSPredicate(format: "%@ >= %K", dateFrom as NSDate, #keyPath(ModelType.date))
应该替换为 let fromPredicate = NSPredicate(format: "%@ <= %K", dateFrom as NSDate, #keyPath(ModelType.date))
(请注意,将大于或等于改为小于或等于)。 - otusweb//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)
let fromPredicate = NSPredicate(format: "datetime >= %@", dateFrom as NSDate)
let toPredicate = NSPredicate(format: "datetime < %@", dateToUnwrapped as NSDate)
... "datetime" 是该属性的名称。