简体   繁体   中英

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!

Use NSCalendar to calculate the start and end of the selected date and create a predicate:

// get the current calendar
let calendar = NSCalendar.currentCalendar()
// get the start of the day of the selected date
let startDate = calendar.startOfDayForDate(calendarSelectedNSDate)
// get the start of the day after the selected date
let endDate = calendar.dateByAddingUnit(.Day, value: 1, toDate: startDate, options: NSCalendarOptions())!
// create a predicate to filter between start date and end date
let predicate = NSPredicate(format: "dateAdded >= %@ AND dateAdded < %@", startDate, endDate)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM