3 回答

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

TA貢獻1811條經驗 獲得超6個贊
我不知道您是否曾問過這個問題,但是如果您只想比較NSDate的日期部分,則必須使用NSCalendar和NSDateComponents刪除時間部分。
這樣的事情應該作為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 關注
- 630 瀏覽
添加回答
舉報