2012-03-27 64 views
0

這裏困惑......我有兩個日期,我的NSLog安慰並獲得其中: 日期爲2011-03-30 13:33:57 +0000 - 2011-03-28 13:33:57 +0000不能比較兩個NSDates

一個日期顯然晚於其他...然而,在代碼低於它不要緊,如果我使用[dateUSERPREFS laterDate:dateXML][dateUSERPREFS earlierDate:dateXML]我得到「我們得到第一中頻」顯示在控制檯?

任何想法?謝謝,

NSDate *dateXML = [df dateFromString:last_modifiedXML]; 
NSDate *dateUSERPREFS = [df dateFromString:last_modifiedUSERPREFS]; 

NSLog(@"dates are %@ - %@", dateXML, dateUSERPREFS); 

if ([dateUSERPREFS laterDate:dateXML]) {   
    NSLog(@"we get first IF"); 
} 

回答

12

[aDate laterDate:anotherDate]返回一個NSDate,而不是一個BOOL。具體來說,它返回兩個日期中較晚的日期。

你想用compare:代替:

NSComparisonResult comparisonResult = [dateUSERPREFS compare:dateXML]; 
if (comparisonResult == NSOrderedAscending) { 
    // case where dateUSERPREFS is before dateXML 
} else if (comparisonResult == NSOrderedSame) { 
    // both dates are the same 
} else if (comparisonResult == NSOrderedDescending) { 
    // this could have just been a plain else; dateUSERPrefs after dateXML 
} 

或者,你可以使用[dateUSERPREFS timeIntervalSinceDate:dateXML]它給你的(簽名)dateXMLdateUSERPREFS秒數。

+1

+1。或者timeIntervalSinceDate:以秒爲單位給出差異(如果接收者較早,則爲負值)。 – danh 2012-03-27 16:16:44

+0

非常感謝。如果這兩個日期雖然彼此相等,但是呢? – sayguh 2012-03-27 16:17:46

+0

查看我的更新回答 – yuji 2012-03-27 16:21:20

1

-[NSDate laterDate:]返回NSDate *不是BOOL,而這不會是Null,所以條件將永遠是正確的。

嘗試-[NSDate compare:]其中有簽名:

- (NSComparisonResult)compare:(NSDate *)anotherDate 

然後,您可以在您的if條件,這是我相信你正在努力實現在你的問題的代碼有什麼比較NSComparisonResult

(當然,你可以繼續使用laterDate:,只是比較原始對象的平等,但我覺得compare:讓更多的直觀的邏輯)