我有一个带有NSDate对象的NSMutableArray“NewDate”
(
"2013-08-11 20:26:11 +0000",
"2013-08-11 20:26:11 +0000",
"2013-08-12 06:22:38 +0000",
"2013-08-12 07:24:14 +0000",
"2013-08-12 08:04:05 +0000"
)
我想使用今天日期(8月12日)的对象从这个数组中创建一个新数组
我的代码:
NSCalendar *calendar = [NSCalendar currentCalendar];
NSDateComponents *components = [calendar components:(NSYearCalendarUnit | NSMonthCalendarUnit | NSDayCalendarUnit) fromDate:[NSDate date]];
[components setTimeZone:[NSTimeZone timeZoneForSecondsFromGMT:0]];
NSDate *firstDate = [calendar dateFromComponents:components];
[components setMonth:0];
[components setDay:1];
[components setYear:0];
NSDate *secondDate = [calendar dateByAddingComponents:components toDate:firstDate options:0];
NSPredicate *firstPredicate = [NSPredicate predicateWithFormat:@"startDate > %@", firstDate];
NSPredicate *secondPredicate = [NSPredicate predicateWithFormat:@"startDate < %@", secondDate];
NSPredicate *predicate = [NSCompoundPredicate andPredicateWithSubpredicates:[NSArray arrayWithObjects:firstPredicate, secondPredicate, nil]];
NSMutableArray *results = [newDate filteredArrayUsingPredicate:predicate];
NSLog(@"%@",result);
但是在创建“结果”时它给了我错误:
*** Terminating app due to uncaught exception 'NSUnknownKeyException', reason: '[<__NSDate 0x72a0ee0> valueForUndefinedKey:]: this class is not key value coding-compliant for the key startDate.'
我做错了什么? 谢谢你的帮助。
答案 0 :(得分:1)
尝试使用以下代码。
array = {&#34; 2013-08-11 20:26:11 + 0000&#34;, &#34; 2013-08-11 20:26:11 + 0000&#34;, &#34; 2013-08-12 06:22:38 + 0000&#34;, &#34; 2013-08-12 07:24:14 + 0000&#34;, &#34; 2013-08-12 08:04:05 + 0000&#34;}; /////示例。
NSMutableArray *newArray=[[NSMutableArray alloc]init];
NSDate *today=[NSDate date];
NSComparisonResult result;
//has three possible values: NSOrderedSame,NSOrderedDescending, NSOrderedAscending
for(int i=0;i<array.count;i++)
{
result = [today compare:[array objectAtIndex:i]];
if(result==NSOrderedDescending)//////If matches with today's date.
{
[newArray addObject:[array objectAtIndex:i]];
}
}
答案 1 :(得分:0)
试试这个..
- (NSComparisonResult)compareDateOnly:(NSDate *)otherDate {
NSUInteger dateFlags = NSYearCalendarUnit|NSMonthCalendarUnit|NSDayCalendarUnit;
NSCalendar *gregorianCalendar = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease];
NSDateComponents *selfComponents = [gregorianCalendar components:dateFlags fromDate:self];
NSDate *selfDateOnly = [gregorianCalendar dateFromComponents:selfComponents];
NSDateComponents *otherCompents = [gregorianCalendar components:dateFlags fromDate:otherDate];
NSDate *otherDateOnly = [gregorianCalendar dateFromComponents:otherCompents];
return [selfDateOnly compare:otherDateOnly];
}