NSPredicate to filter only on “year” part of a date field

杀马特。学长 韩版系。学妹 提交于 2019-12-06 01:37:31

问题


I have an entity with a date field and I would like to select the records for a given year. How to build a NSPredicate for the job? Didn't find anything about date functions (if any) in Core Data

thanks


回答1:


A possible method:

Step 1) See "Creating a Date from Components" from Apple's "Date and Time Programming Guide." Make an NSDate representing the beginning of the year, and an NSDate representing the end of the year.

Step 2) Then you could build a predicate that searches for objects with date attrs that are greater than the first date and less than the last date.

The predicate would look something like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@“(inceptionDate > %@) AND (inceptionDate < %@)”, dateBeginYear, dateEndYear];



回答2:


Eventually I did more or less as suggested by Wienke. To create the predicate that fetches the records for a certain year(s), I did like 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]];  }


来源:https://stackoverflow.com/questions/5365258/nspredicate-to-filter-only-on-year-part-of-a-date-field

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!