Core Data- predicate with dates

Z S picture Z S · Jul 25, 2011 · Viewed 12.9k times · Source

I'm stumped trying to write a predicate for "Recently Completed" tasks, i.e. show the task if it was completed within the last 7 days. I think I need to do something like this: "if NOW < dateCompleted + 7 days".

The dateCompleted is an attribute on the table, but I'm not sure how I'm supposed to get it's value and add 7 days to it from within the predicate. I guess I need to fetch the attribute value first before writing the NSPredicate, but how? I don't have access to the managedObject at this point.

This might be close the solution, but I can't figure out how to define 'oneWeek' and I don't think you can just add values when defining the predicate:

NSPredicate *pred = [NSPredicate predicateWithFormat:@"%@ < todoCompletedDate + %@", [NSDate date], oneWeek];

Answer

mmccomb picture mmccomb · Jul 25, 2011

You're almost there.

Firstly you need to define your date range. To do that you'll want to start with today's date and then add a weeks worth of days to find the end of the valid range. Once you have that range you can build your predicate to find all tasks with a due date >= start and <= end. Here's an extract from some code I've written to do something very similar...

NSDate *today = [NSDate date];
NSDate *startOfToday = [DateHelper startOfDay:today];
NSDate *endOfWeek = [DateHelper addDaysToDate:today daysToAdd:6];
return [NSPredicate predicateWithFormat:@"(dueDate >= %@) AND (dueDate <= %@) AND complete == 0", startOfToday, endOfWeek];