2010-10-26 113 views
4

,如果我有兩個nsdatecomponent,我想知道,如果在第一個對象的時間比第二大。比較兩個nsdatecomponent

例如:

if (nsdatecomponentObject1 > nsdatecomponentObject2) 
{ 
    //something 
} 

因爲這樣做不工作,我可怎麼辦呢?

+0

什麼意思的兩個NSDateComponents比較同一月份,日期和年份是否有指定的工作日,而另一個沒有?這些規則在哪裏指定? – titaniumdecoy 2011-12-23 23:37:12

回答

6

NSDateComponentNSDate上使用compare:

if([[nsdatecomponentObject1 date] compare:[nsdatecomponentObject2 date]] == NSOrderedAscending) 
+0

Mac開發人員注意事項:此方法僅存在於iOS版本的Foundation中(至今爲止,無論如何 - 它可能在Lion中)。 – Chuck 2010-10-26 16:49:03

+2

我的比較結果總是爲0,爲什麼? – alex 2010-10-26 17:24:21

+0

我認爲你的回答只有比較日期,因爲我thow nsdateobjects富人同樣的日期,但不一樣的「組件Seconde系列」,其結果是nsorderedsame。 – alex 2010-10-26 17:40:54

0

權(唯一的)的方式來比較「上即時」兩個NSDateComponents,是使用NSCalendar對象:

NSCalendar *gregorian = [[[NSCalendar alloc] initWithCalendarIdentifier:NSGregorianCalendar] autorelease]; 

switch([[gregorian dateFromComponents:oneNSDateComponents] compare:[gregorian dateFromComponents:anotherNSDateComponents]]) { 
    case NSOrderedSame: 
     NSLog(@"orderSame"); 
     break; 
    case NSOrderedAscending: 
     NSLog(@"orderAscending"); 
     break; 
    case NSOrderedDescending: 
     NSLog(@"orderDescending"); 
     break; 
}