You cannot just compare date and date:
let today = Date()
let datePredicate = NSPredicate(format: "date == %@", today)
This will not show anything, since it is unlikely that your date is the EXACT date of the comparison (it includes seconds and milliseconds)
The solution is this:
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
let dateFrom = calendar.startOfDay(for: Date())
let components = calendar.dateComponents([.year, .month, .day, .hour, .minute],from: dateFrom)
components.day! += 1
let dateTo = calendar.date(from: components)!
let datePredicate = NSPredicate(format: "(%@ <= date) AND (date < %@)", argumentArray: [dateFrom, dateTo])
fetchRequest.predicate = datePredicate
This is by far the easiest and shortest way to display only those objects that have today.
source
share