Search code examples
iosswiftcore-data

Swift Core Data Fetch results from a certain date


I'm fairly new to ioS dev so this might be obvious.

With Core Data, I have an Entity : 'Post' , with an attribute for "dateAdded".

When the user selects an NSDate on a calendar- I want to fetch all the entries on that day only and load that into a table.

I was thinking of using a predicate where dateAdded (NSDate) would be equal to the calendarSelectedNSDate. But I don't think that would work as their NSDates would be different because of different times.

I would really appreciate a solution! Thank you!


Solution

  • Use (NS)Calendar to calculate the start and end of the selected date and create a predicate:

    // get the current calendar
    let calendar = Calendar.current
    // get the start of the day of the selected date
    let startDate = calendar.startOfDay(for: calendarSelectedNSDate)
    // get the start of the day after the selected date
    let endDate = calendar.date(byAdding: .day, value: 1, to: startDate, options: .matchNextTime)!
    // create a predicate to filter between start date and end date
    let predicate = NSPredicate(format: "dateAdded >= %@ AND dateAdded < %@", startDate as NSDate, endDate as NSDate)