NSPredicate两个日期之间的范围没有按预期工作 [英] NSPredicate for range between two dates is not working as expected
问题描述
我有两个 NSDate
s:
NSDateFormatter *df = [[NSDateFormatter alloc] init];
[df setDateFormat:@"MM/dd/yyyy"];
NSDate *rangeStart = [df dateFromString: @"03/03/2013"];
NSDate *rangeEnd = [df dateFromString: @"10/04/2013"];
这个谓词:
request.predicate = [NSPredicate predicateWithFormat:@"createdDate >= %@ AND createdDate <= %@", rangeStart, rangeEnd];
但即使谓词的第二部分专门使用< =
它返回对象直到前一天(即 10/03/2013
)。
But even though the second part of the predicate specifically uses a <=
it is returning objects up until the day before (that is 10/03/2013
).
我也尝试构造这样的谓词:
I also tried constructing the predicate like this:
NSPredicate *dateStartPredicate = [NSPredicate predicateWithFormat:@"createdDate >= %@", rangeStart];
NSPredicate *dateEndPredicate = [NSPredicate predicateWithFormat:@"createdDate <= %@", rangeEnd];
NSPredicate *finalPredicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:dateStartPredicate, dateEndPredicate, nil]];
但我得到了相同的结果。难道我做错了什么?这实际上是预期的行为吗?如果是,如何将 rangeEnd
设置为第二天?
But I'm getting the same results. Am I doing something wrong? Is this actually the expected behavior? If it is, how can set the rangeEnd
to the next day?
谢谢
推荐答案
NSDate
对象也包括时间。当您将没有时间的日期传递给 dateFromString:
方法时,假定相应日期的午夜,即只有午夜时发生的项目将返回 true
小于或等于表达式。
NSDate
objects include the time as well. When you pass a date with no time to the dateFromString:
method, the midnight of the corresponding day is assumed, i.e. only the items that happen on midnight would return true
in the less than or equal expression.
有两种常用方法可以解决它:
There are two common ways of solving it:
- 将一天添加到
rangeEnd
,并使用小于而不是小于或等于,或 - 将时间添加到
rangeEnd
日期(这不太理想,因为您需要在长字符串中指定时间,或错过当天最后一秒发生的事情。)
- Add one day to
rangeEnd
, and use "less than" instead of "less than or equal", or - Add the time to the
rangeEnd
date (this is not ideal, because you would either need to specify the time in a long string, or miss the items that happened on the last second of the day).
以下是使用第一种方法的方法:
Here is how to use the first approach:
request.predicate = [NSPredicate
predicateWithFormat:@"createdDate >= %@ AND createdDate < %@"
, rangeStart
, [rangeEnd dateByAddingTimeInterval:60*60*24]
];
这篇关于NSPredicate两个日期之间的范围没有按预期工作的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!