形成谓词以在日期之间进行过滤 [英] Forming a predicate to filter between dates

查看:137
本文介绍了形成谓词以在日期之间进行过滤的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

说我有两个日期:

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

我有一个Core Data对象称为MBDate,它有一个NSDate属性。我想得到所有MBDate的天,包括天之间和之间的天。所以它应该忽略小时,秒和分钟,只是得到在8/29 - 12/01之间的所有日子。

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.

像:

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?

推荐答案

您可以使用NSDateComponents设置低和高日期,并在谓词中使用这些。

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

这篇关于形成谓词以在日期之间进行过滤的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆