Skip to content

Instantly share code, notes, and snippets.

@zdam
Created April 3, 2011 23:37
Show Gist options
  • Save zdam/900929 to your computer and use it in GitHub Desktop.
Save zdam/900929 to your computer and use it in GitHub Desktop.
Core Data fetch by Date
+(NSPredicate *)dateMatcher:(NSDate *)date forAttribute:(NSString *)attributeName{
//First set the unit flags you want automatically put into your date from an NSDate object
unsigned startUnitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
//now create an NSCalendar object
NSCalendar *startCal = [NSCalendar currentCalendar];
//Use the NSCalendar object to create an NSDateComponents object from the date you are interested in rounding
//In this case we are just using the time now by calling [NSDate date]
NSDateComponents *minDateComps = [startCal components:startUnitFlags fromDate:[NSDate date]];
//Now we use the NSCalendar object again to generate a date from the date components object
NSDate *startDate = [startCal dateFromComponents:minDateComps];
//First set the unit flags you want automatically put into your date from an NSDate object
unsigned unitFlags = NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit;
//now create an NSCalendar object
NSCalendar *cal = [NSCalendar currentCalendar];
//Use the NSCalendar object to create an NSDateComponents object from the date you are interested in rounding
//In this case we are just using the time now by calling [NSDate date]
NSDateComponents *maxDateComps = [cal components:unitFlags fromDate:[NSDate date]];
//now set the hours, minutes and seconds to the end of the day
maxDateComps.hour = 23;
maxDateComps.minute = 59;
maxDateComps.second = 59;
//Now we use the NSCalendar object again to generate a date from the date components object
NSDate *endDate = [cal dateFromComponents:maxDateComps];
// Finally create the predicate with the correct format
return [NSPredicate predicateWithFormat:@"(%K >= %@) AND (%K <= %@)",attributeName, startDate, attributeName, endDate];
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment