NSPredicate to filter only on the "annual" part of the date field

I have an object with a date field, and I would like to select records for a given year. How to create an NSPredicate to work? Did not find anything about date functions (if any) in Core Data p>

thanks

+6
date ios iphone core-data nspredicate
source share
2 answers

Possible method:

Step 1) See “Creating a Date from Components” in Apple's “Date and Time Programming Guide”. Create an NSDate representing the beginning of the year and an NSDate representing the end of the year.

Step 2) Then you can create a predicate that searches for objects with dates that are greater than the first date and less than the last date.

The predicate will look something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(inceptionDate > %@) AND (inceptionDate < %@)", dateBeginYear, dateEndYear]; 
+1
source share

In the end, I did more or less, as Vinka suggested. To create a predicate that retrieves records for a specific year (s), I liked this:

 - (NSPredicate*) predicateFromYear:(NSInteger)start span:(NSInteger)aSpan { NSCalendar *cal = [NSCalendar currentCalendar]; NSDateComponents *dc = [NSDateComponents new]; [dc setYear:start]; NSDate *startDate,*endDate; startDate = [cal dateFromComponents:dc]; [dc setYear:aSpan]; endDate = [cal dateByAddingComponents:dc toDate:startDate options:0]; [dc release]; return [NSPredicate predicateWithFormat: @"date >= CAST(%f, \"NSDate\") AND date < CAST(%f, \"NSDate\")", [startDate timeIntervalSinceReferenceDate], [endDate timeIntervalSinceReferenceDate]]; } 
+5
source share

All Articles