Building on the previous answers, an update and alternative method using Swift 5.x
func predicateForDayUsingDate(_ date: Date) -> NSPredicate {
var calendar = Calendar.current
calendar.timeZone = NSTimeZone.local
// following creates exact midnight 12:00:00:000 AM of day
let startOfDay = calendar.startOfDay(for: date)
// following creates exact midnight 12:00:00:000 AM of next day
let endOfDay = calendar.date(byAdding: .day, value: 1, to: startOfDay)!
return NSPredicate(format: "day >= %@ AND day < %@", argumentArray: [startOfDay, endOfDay])
}
If you'd prefer to create the time for endOfDay
as 11:59:59 PM, you can instead include...
let endOfDayLessOneSecond = endOfDay.addingTimeInterval(TimeInterval(-1))
but then you might change the NSPredicate to...
return NSPredicate(format: "day >= %@ AND day <= %@", argumentArray: [startOfDay, endOfDayLessOneSecond])
...with specific note of the change from day < %@
to day <= %@
.