0

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?

momo
  • 125
  • 6
  • 1
    "One day has 86400 seconds" this is incorrect. There are days with less seconds (daylight time saving) and different calendars with different length of days. Check out WWDC 2013 session about date and time management. – art-divin Oct 02 '13 at 10:22
  • You are right, but this app will only be used in a controlled environment in one country, so this will not cause unexpected behaviors. – momo Oct 02 '13 at 10:34
  • Does the order of date1 and date2 matter? Are they always in the same order? – David Rönnqvist Oct 02 '13 at 10:40
  • date2 is always greater or equal then date1 – momo Oct 02 '13 at 10:50

1 Answers1

1

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.

ilya n.
  • 18,398
  • 15
  • 71
  • 89
  • That would be the prefered solution, but the number of days can be edited by the user. This would then cause an update of every object to re-calculate the new date differences. – momo Oct 02 '13 at 10:47
  • This is the same solution that I probably would go for but for a completely different reason. date2-date1 most likely reflects some real data in the OP's data type. Maybe it's the duration of an event, the number of days of a vacation or some other thing that you could put a name on. The predicate and other related code would be much cleaner if it was `"numberOfDays > 7"` or `myEntity.numberOfDays;` – David Rönnqvist Oct 02 '13 at 10:48
  • @mr. mo, so what? you define integer `dateDifferenceInDays`, user inputs `targetNumberOfDays` and you feed a predicate `dateDifferenceInDays > targetNumbersOfDays` to Core Data. Databases have been optimized to death to handle exactly those types of predicates. – ilya n. Oct 02 '13 at 10:56
  • Oh, you are totally right! I must have mixed something up in my mind :) – momo Oct 02 '13 at 11:01