2015-02-23 47 views
0

比較,我知道如何將兩個的NSDate之間的差異得到如下的iOS - NSDate的另一個NSDate的

NSTimeInterval timeInterval = [[NSDate date] timeIntervalSinceDate:anyPreviousDate]; 

,我知道這將返回我NSTimeInterval正秒。我想知道的是,如果我的anyPreviousDate大於[NSDate date],它將返回,即anyPreviousDate尚未通過,它將在未來發生。

只是好奇,如果有人已經這樣做過。

在此先感謝。

+2

從更大的返回

NSOrderedDescending小返回NSOrderedAscending doc:接收者和anotherDate參數之間的時間間隔。如果接收者早於anotherDate,則返回值爲負值。如果anotherDate爲零,則結果未定義。 – Andrea 2015-02-23 10:17:31

回答

1

我發現了另一個很好的方法來做同樣的事情... 這裏是代碼,我想與它分享它與計算器。 Cocoa has couple of methods for this

在NSDate的

– isEqualToDate: 
– earlierDate: 
– laterDate: 
– compare: 

當您使用- (NSComparisonResult)compare:(NSDate *)anotherDate,你回來的其中之一:

The receiver and anotherDate are exactly equal to each other, NSOrderedSame 
The receiver is later in time than anotherDate, NSOrderedDescending 
The receiver is earlier in time than anotherDate, NSOrderedAscending. 

例如:

NSDate * now = [NSDate date]; 
NSDate * mile = [[NSDate alloc] initWithString:@"2001-03-24 10:45:32 +0600"]; 
NSComparisonResult result = [now compare:mile]; 

NSLog(@"%@", now); 
NSLog(@"%@", mile); 

switch (result) 
{ 
    case NSOrderedAscending: NSLog(@"%@ is in future from %@", mile, now); break; 
    case NSOrderedDescending: NSLog(@"%@ is in past from %@", mile, now); break; 
    case NSOrderedSame: NSLog(@"%@ is the same as %@", mile, now); break; 
    default: NSLog(@"erorr dates %@, %@", mile, now); break; 
} 

[mile release]; 
0

如果anyPreviousDate實際上是將來10秒,那麼您的代碼將返回-10.0。經常發生的是,你定義了將來某個時間的NSDate(例如,從現在起一分鐘後做一些事情),所以這根本就不是特殊的。

1
if([previousDate compare:[NSDate date]] == NSOrderedDescending){ 
    // Previous date is greater than current date.i.e. previous date 
    //is still to come 
    }else{ 
    //Previous date is smaller then current date.i.e. previous date 
    //has passed. 
    } 

比較NSDate對象的方法返回NSComparisonResult,它是一個枚舉。

NSComparisonResult具有以下值。如果離開

NSOrderedSame返回,右操作數相等

如果左操作數大於右操作數,如果FT操作數大於右操作數