我正在使用以下代碼來比較兩個NSDates。結果稍後在瞬態屬性中用於組織表格視圖節中的對象。我可以確保核心數據存儲中有足夠的對象,以便提供三種可能的結果,但NSLog顯示選項tmp = @「1」,從不拋出。比較iOS中的日期問題
-(NSString *)sectionIdentifier{
[self willAccessValueForKey:@"sectionIdentifier"];
NSString *tmp = [self primitiveValueForKey:@"sectionIdentifier"];
[self didAccessValueForKey:@"sectionIdentifier"];
if (!tmp){
NSDate *date = self.todoDueDate;
NSDate *todayDate = [NSDate date];
NSLog(@"date= %@",date);
NSLog(@"todayDate = %@",todayDate);
if([date
compare:todayDate] == NSOrderedSame) {
tmp = @"1";//TODAY
}
else if([date
compare:todayDate] == NSOrderedDescending){
tmp = @"2";//OVERDUE
}
else if ([date
compare:todayDate] == NSOrderedAscending){
tmp [email protected]"0";//UPCOMING
}
NSLog(@"Tmp= %@",tmp);
[self setPrimitiveValue:tmp forKey:@"sectionIdentifier"];
}
這裏日誌:
2014-01-15 10:10:52.732 To-Do Pro Light[21458:a0b] date = 2014-01-10 19:53:19 +0000
2014-01-15 10:10:52.735 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.742 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.743 To-Do Pro Light[21458:a0b] date = 2014-01-14 17:45:45 +0000
2014-01-15 10:10:52.746 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.747 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.748 To-Do Pro Light[21458:a0b] date = 2014-01-14 17:57:44 +0000
2014-01-15 10:10:52.749 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.751 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.753 To-Do Pro Light[21458:a0b] date = 2014-01-15 16:31:48 +0000
2014-01-15 10:10:52.755 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.756 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.758 To-Do Pro Light[21458:a0b] date = 2014-01-15 16:32:06 +0000
2014-01-15 10:10:52.759 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.761 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.762 To-Do Pro Light[21458:a0b] date = 2014-01-15 17:03:40 +0000
2014-01-15 10:10:52.763 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.764 To-Do Pro Light[21458:a0b] Tmp= 0
2014-01-15 10:10:52.766 To-Do Pro Light[21458:a0b] date = 2014-01-15 18:33:48 +0000
2014-01-15 10:10:52.767 To-Do Pro Light[21458:a0b] todayDate = 2014-01-15 17:10:52 +0000
2014-01-15 10:10:52.768 To-Do Pro Light[21458:a0b] Tmp= 2
我在做什麼錯?
您日誌中的任何'NSDate'對象都不相同。你爲什麼期望看到'Tmp = 1'?請記住,比較中包含時間(以毫秒爲單位)。 – rmaddy
以及如何比較日期而不考慮時間,只有年,月和日? – mvasco
@mvasco:NSDateComponents可以在這裏幫助。 – Larme