我發現了另一個很好的方法來做同樣的事情... 這裏是代碼,我想與它分享它與計算器。 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];
從更大的返回
NSOrderedDescending小返回NSOrderedAscending doc:接收者和anotherDate參數之間的時間間隔。如果接收者早於anotherDate,則返回值爲負值。如果anotherDate爲零,則結果未定義。 – Andrea 2015-02-23 10:17:31