momo
momo

Reputation: 125

How to filter with NSPredicate by date difference greater then x days

I have a Core Data model with two date properties (date1 and date2) and would like to fetch all objects which have date2 - date1 > x days. What I already tried:

NSFetchRequest *fetchRequest = [NSFetchRequest fetchRequestWithEntityName:@"MyEntity"];
fetchRequest.predicate = [NSPredicate predicateWithFormat:@"date1 != nil AND date2 != nil AND date2 - date1 > %d", x*86400];

My understanding of NSDate is that this is just a wrapper around a Unix timestamp and Core Data compares two dates by comparing the timestamps internally. One day has 86400 seconds, so the predicate above makes totaly sense to me, but somehow it also returns objects with less then x days difference.

What am I doing wrong?

Upvotes: 0

Views: 976

Answers (1)

ilya n.
ilya n.

Reputation: 18816

Why not store the date difference as a separate field?

It will be radically faster than any on-the-fly calculation. And you can do that in the date's setters.

Upvotes: 1

Related Questions