Snowman
Snowman

Reputation: 32061

Forming a predicate to filter between dates

Say I have two dates:

minDate:2012-08-29 12:22:17 +0000
maxDate:2011-12-01 18:14:38 +0000

I have a Core Data object called MBDate which has an NSDate property. I want to get all MBDate's with days including and in between the days above. So it should disregard the hours, seconds, and minutes, and just get all days in between and including 8/29 - 12/01.

Something like:

predicate = [NSPredicate predicateWithFormat:@"date < %@ AND date > %@", maxDate, minDate];

But I'm not sure how I would tell it to disregard the hours and minutes and just look at the days. Any ideas?

Upvotes: 0

Views: 997

Answers (1)

iTukker
iTukker

Reputation: 2083

You could use NSDateComponents to set a 'low' and 'high' date and use these in your predicate.

NSCalendar *gregorian = [[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar];
gregorian.timeZone = [NSTimeZone timeZoneWithAbbreviation"@"UTC"];

NSDateComponents *dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:minDate];

[dateComponents setHour:0];
[dateComponents setMinute:0];
[dateComponents setSecond:0];
NSDate *lowDate = [gregorian dateFromComponents:dateComponents];

dateComponents = [gregorian components:(NSDayCalendarUnit | NSMonthCalendarUnit | NSYearCalendarUnit) fromDate:maxDate];

[dateComponents setHour:23];
[dateComponents setMinute:59];
[dateComponents setSecond:59];
NSDate *highDate = [gregorian dateFromComponents:dateComponents];

Upvotes: 3

Related Questions