Core Data Predicate Filter By Today's Date

人盡茶涼 提交于 2019-12-03 20:07:10

问题


I had issues with this and I haven't found a proper answer on SO so I'll leave a small tutorial here.

The goal is to filter fetched objects by today's date.

Note: It's Swift 3 compatible.


回答1:


You can't simply use to compare your date to today's date:

let today = Date()
let datePredicate = NSPredicate(format: "%K == %@", #keyPath(ModelType.date), today)

It will show you nothing since it's unlikely that your date is the EXACT comparison date (it includes seconds & milliseconds too)

The solution is this:

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

It's by far the easiest & shortest way of showing only objects which have today's date.




回答2:


In swift4, Lawrence413's can be simplify a bit:

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

It get rid of the component part, makes the code have better readability.



来源:https://stackoverflow.com/questions/40312105/core-data-predicate-filter-by-todays-date

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!