Forming a predicate to filter between dates

杀马特。学长 韩版系。学妹 提交于 2019-12-13 03:16:45

问题


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?


回答1:


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];


来源:https://stackoverflow.com/questions/11179128/forming-a-predicate-to-filter-between-dates

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