iOS - 将 NSDate 与另一个 NSDate 进行比较

iOS - Comparing NSDate with another NSDate

我知道如何获取两个 NSDate 之间的差异,如下所示

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

而且我知道它会 return 我 NSTimeInterval 在积极的几秒钟内。我想知道的是,如果我的 anyPreviousDate 大于 [NSDate date],即 anyPreviousDate 尚未通过,它将 return 是什么,它将在未来出现。

只是好奇之前是否有人这样做过。

提前致谢。

如果 anyPreviousDate 实际上是十秒后,那么您的代码将 return -10.0。您经常会定义未来某个时间的 NSDates(例如从现在开始一分钟后做某事),所以这一点也不罕见。

我发现了另一种非常好的方法来做同样的事情...... 这是代码,我想与 Whosebug 分享。 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];
   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 对象的比较方法returns NSComparisonResult,它是一个枚举。

NSComparisonResult 具有以下值。

如果左右操作数相等则返回NSOrderedSame

如果左操作数小于右操作数,则返回NSOrderedAscending

如果 ft 操作数大于右操作数,则返回 NSOrderedDescending

this's a screenshot to see

         NSDate * savedDate = [recordsDic[record.transactionId] modifiedDate];
         NSDate * newDate = record.modifiedDate;
         NSComparisonResult comparisonResult = [newDate compare:savedDate];
         NSTimeInterval timeInterval = [newDate timeIntervalSinceDate:savedDate];
         NSLog(@"\nsavedDate: %@   \nnewDate  : %@  \n===> timeInterval: %f",savedDate,newDate,timeInterval);
         if (comparisonResult == NSOrderedSame) {
             NSLog(@"they are same!!!!");
         } else {
             NSLog(@"they are NOT same!!!!");
         }
Console log:
2019-04-11 17:26:47.903059+0800 xxxxx[19268:24419134] 
savedDate: Thu Apr 11 15:47:23 2019   
newDate  : Thu Apr 11 15:47:23 2019  
===> timeInterval: 0.000365
2019-04-11 17:26:47.903193+0800 xxxxx[19268:24419134] they are NOT same!!!!

你相信吗!?但这是真的,我花了将近一整天的时间来解决这个问题。因为这不会一直发生!!! 所以我强烈推荐: 1. 不要使用实例方法“- (NSComparisonResult)compare:(NSDate *)other;”比较,你会看到一些真正有线的东西,你无法弄清楚。 2. timeIntervalSinceDate 更精确。