4

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!

  • You are thinking in right direction. You have to keep the date format same. So while you are storing the date in coreData you would be knowing the format or you change the format accordingly. Now when user selects the date first convert the date into required format and use your predicate. – Arun Gupta Mar 20 '16 at 16:56

1 Answers1

8

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)
vadian
  • 274,689
  • 30
  • 353
  • 361
  • If I use the above predicate for timestamps saved as double all records between 11:59PM & 12:00 AM are ignored (60 seconds interval) . Any hints on why this might be happening ? – Nikhil Muskur Sep 17 '21 at 05:35
  • Actally this predicate is supposed to work correctly if you consider only the start date and add one day. – vadian Sep 17 '21 at 06:16
  • Yup I am doing the same thing, adding 1 day to the start date to get the end date, the only difference is that I am using timestamps instead of Date. If possible can you please check my question : https://stackoverflow.com/q/69210582/9718262 – Nikhil Muskur Sep 17 '21 at 06:30