Home > OS >  Core Data NSPredicate - Match Dates
Core Data NSPredicate - Match Dates

Time:03-16

I have an entity in core data that stores a Date property date. I have an @State property in my View selectedDate that is of type Date.

I want to use a fetch request to retrieve all of the entities in the database with a date matching selectedDate. I want to do this exclusive of the time; for example selectedDate could be 15/03/2022 at 12:07pm, and date could be 15/03/2022 at 9:05am - I would like these to be matched.

I have tried to use the following (although this will not achieve the desired time behaviour):

request.predicate = NSPredicate(format: "date == %@", selectedDate.timeIntervalSince1970)

However, when running the app I get the following error, on the predicate line:

Thread 1: EXC_BAD_ACCESS (code=1, address=0x41d88c207fdc4b4d)

Does anyone know how to do this?

CodePudding user response:

First of all the exception occurs because the placeholder %@ is wrong. %@ is for objects, a Double value is represented by %f.

Second of all if you want to fetch all dates which are in a specific day you have to create a date range (0:00–23:59) of that day.

Using Calendar you get 0:00 with startOfDay(for:) and the end of the day by adding a day and the < operator.

For example

let calendar = Calendar.current
let startDate = calendar.startOfDay(for: selectedDate)
let endDate = calendar.date(byAdding: .day, value: 1, to: startDate)!
let predicate = NSPredicate(format: "date >= %@ AND date < %@", argumentArray: [startDate, endDate]))
  • Related