I am using CoreData for a project - My CoreData entity has an attribute "date", type Date. I am trying to filter the data based on mm/dd/yy only. Here is what I have so far
fetchRequest.predicate = NSPredicate(format: "date = %@", date as! NSDate)
This doesn't work because "date" includes the time, which makes each entry different even though the calendar date is the same.
I have tried parsing the date into a string mm/dd/yy and changing the format to "date CONTAINS stringDate", but that didn't work- I don't think I should be able to search for a string inside a Date.
I have looked through the documentation on predicates, but I cannot figure out how to apply to type Date.
CodePudding user response:
The approach you need to take here is to create a predicate where you test if the date attribute is between the start of the day and at the end of the day so you will get a match for any time of that day.
let predicate = NSPredicate(format: "date >= %@ && date <= %@",
argumentArray: [startDate, endDate]
where you calculate the dates from a given date inputDate
as
let startDate = Calendar.current.startOfDay(for: inputDate)
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)!