2013-08-12 123 views
0

的陣列獲取與當前日期的日期陣列時,我有一個NSMutableArray「NewDate」與NSDate的對象錯誤的日期

(
"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

那麼,對於初學者,你正在編寫一個完全虛構的屬性,稱爲「startDate」。你試圖用你的第一個和第二個謂詞做什麼? – borrrden

回答

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]; 
} 
+1

我不知道你是否問過這個問題,但是如果你只想比較一個NSDate的日期組件,你必須使用NSCalendar和NSDateComponents來刪除時間組件。 像這樣的東西應該作爲NSDate的一個類別: – iosLearner

1

嘗試用下面的代碼。

array = {「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「}; /////舉例。

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