Search code examples
iosobjective-cnsdatenstimeinterval

iOS - Comparing NSDate with another NSDate


i know how to get difference between two NSDate as follow

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

and i know it will return me NSTimeInterval in positive seconds. what I want to know is what it will return if my anyPreviousDate is greater than [NSDate date] i.e. anyPreviousDate has not been passed it will come in future.

just curious if anybody has done that before.

Thanks in advance.


Solution

  • I have found another very nice approach to do the same... here is the code, i thought to share it with stackoverflow. Cocoa has couple of methods for this:

    in NSDate

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

    When you use - (NSComparisonResult)compare:(NSDate *)anotherDate ,you get back one of these:

    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.
    

    example:

    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];