问题
I am using datetime picker in form and inserting data as follows to core data entity (attribute)
`appointment.date = appointmentDate.date //it is getting date as well and time
appointment.title = "Appointment"
do {
try managedObjectContext.save()`
and in another viewcontroller i am doing this to filter records based on date. I have a calendar which returns date.
let fetchRequest = NSFetchRequest<NSFetchRequestResult>(entityName: "Appointment")
let sortDescriptor = NSSortDescriptor(key: "date", ascending: true)
fetchRequest.sortDescriptors = [sortDescriptor]
let predicate = NSPredicate(format: "date = %@", calendar.selectedDate! as NSDate)
fetchRequest.predicate = predicate
Trying to filter just by the date (ignoring time) but it is not working(does not show anything).If I remove the predicate all records are displayed.
What is the right way or where am i doing it wrong? Is it a format problem?
回答1:
If you want to filter the records which are in the selected day you have to apply a predicate with start and end date
let startDate = Calendar.current.startOfDay(for: calendar.selectedDate)
let endDate = Calendar.current.date(byAdding: .day, value: 1, to: startDate)
let predicate = NSPredicate(format: "date >= %@ AND date < %@", startDate as NSDate, endDate as NSDate)
来源:https://stackoverflow.com/questions/57204968/filter-by-date-only-from-datetime-datepicker-in-swift