3 回答

TA貢獻(xiàn)1891條經(jīng)驗(yàn) 獲得超3個(gè)贊
根據(jù)蘋果的文件NSDate compare:
返回一個(gè)NSComparisonResult值,該值指示接收者的時(shí)間順序和另一個(gè)給定的日期。
- (NSComparisonResult)compare:(NSDate *)anotherDate
參量 anotherDate
比較接收者的日期。此值不能為nil。如果值為nil,則行為是未定義的,并且在Mac OS X的將來版本中可能會(huì)更改。
返回值
如果:
接收者和anotherDate彼此完全相同, NSOrderedSame
接收器的時(shí)間晚于另一個(gè)日期, NSOrderedDescending
接收者的時(shí)間早于另一個(gè)日期, NSOrderedAscending
換一種說法:
if ([date1 compare:date2] == NSOrderedSame) ...
請(qǐng)注意,在您的特定情況下,閱讀和編寫以下內(nèi)容可能會(huì)更容易:
if ([date2 isEqualToDate:date2]) ...

TA貢獻(xiàn)1811條經(jīng)驗(yàn) 獲得超6個(gè)贊
我不知道您是否曾問過這個(gè)問題,但是如果您只想比較NSDate的日期部分,則必須使用NSCalendar和NSDateComponents刪除時(shí)間部分。
這樣的事情應(yīng)該作為NSDate的類別:
- (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];
}
- 3 回答
- 0 關(guān)注
- 628 瀏覽
添加回答
舉報(bào)