Robby Cohen
Robby Cohen

Reputation: 497

NSPredicate and CoreData - decide if a Date attribute is "today" (or between last night 12am to tonight 12am) on iOS

I'm using a NSFetchedResultsController and a UITableViewController to populate a UITableView from a CoreData database.

I have a NSDate object saved into this Date attribute labeled "startTime". Then I'm trying to only pull todays's data by using a NSPredicate that looks like this:

NSPredicate *predicate = [NSPredicate predicateWithFormat:@"startDate == %@",
                          todaysDate];

I'm getting zero results. I understand this because a NSDate object just hold the number of seconds or milliseconds or whatever since Jan 1 1970 right? So comparing 1111111111111 and 1111111111112, while on the same day, are two distinct NSDate objects that aren't equal.

So, how could the NSPredicate be formatted so that it would do it? I'm going to guess its creating two NSDate objects: one that is at 12am last night, and another for 12am tonight and compare startDate and see if its between these two NSDates.

I'm kind of new to NSPredicate, so how could this be accomplished?

Upvotes: 8

Views: 5300

Answers (1)

yuji
yuji

Reputation: 16725

Use NSCompoundPredicate.

NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];

NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];

Where firstDate is 12am this morning and secondDate is 12am tonight.

P.S. Here's how to get 12am this morning:

NSCalendar *calendar = [NSCalendar calendar]; // gets default calendar
NSCalendarComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit |  NSDayCalendarUnit) fromDate:[NSDate date]]; // gets the year, month, and day for today's date
NSDate *firstDate = [calendar dateFromComponents:components]; // makes a new NSDate keeping only the year, month, and day

To get 12am tonight, change components.day.

Upvotes: 24

Related Questions