2010-10-26 106 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; 
}