Filter by date only from datetime/datepicker in swift

主宰稳场 提交于 2021-01-29 08:24:37

问题


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

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