Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
795 views
in Technique[技术] by (71.8m points)

objective c - Core Data Predicate Date Comparison

Im trying to fetch all the objects in an entity matching a user selectedDate (it's an NSDate). The Core Data code is fine but my predicate keeps returning 0 results, the dates are the same in the database as the user is selecting.

How should the selectedDate be compared with a date from an entity using a predicate?

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"(eDate = %@)", selectedDate];
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

Your predicate looks to be fine.

The reason you're finding zero result are returned however may be that the dates aren't entirely the same.

For example:

05/04/2012 13:37:00 will not match with 05/04/2012 13:37:01 as these two values are not exactly the same.

Do you want to check the date (day, month, year) as well as the time?

If you only want to check the date, you should create a start date and end date and compare them using the user selected date as a frame of reference.

Something similar to this should create a date and time for 00:00:00.

//gather current calendar
NSCalendar *calendar = [NSCalendar currentCalendar];

//gather date components from date
NSDateComponents *dateComponents = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];

//set date components
[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];

//return date relative from date
return [calendar dateFromComponents:dateComponents];

Create another date by setting the hours, minutes and seconds to 23:59:59 and check that your user selected date falls between these ranges.

[NSPredicate predicateWithFormat:@"date BETWEEN %@", [NSArray arrayWithObjects:startOfDay, endOfDay, nil]]

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...