pete
pete

Reputation: 3050

comparing Two NSDate objects not working

I'm learning about how to compare NSDate objects with the isEqualToDateDate method. I don't get why this simple test does not return true and print out the NSLog. Thanks in advance

#import <Foundation/Foundation.h>

int main (int argc, const char * argv[])
{

    NSAutoreleasePool * pool = [[NSAutoreleasePool alloc] init];

    NSDate *myDate =    [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
    NSDate *otherDate = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];

     NSLog(@"myDate    %@",myDate);
     NSLog(@"otherDate %@",otherDate);

    if ([myDate isEqualToDate:otherDate]) {

        NSLog(@"The dates are the same");
    };

    [myDate release];
    [otherDate release];
    [pool drain];
    return 0;
}

Upvotes: 2

Views: 1348

Answers (2)

nicholjs
nicholjs

Reputation: 1762

I believe, and this may be wrong, that since you are using initWithTimeIntervalSinceNow that the objects are being allocated at slightly different times, thus making them unequal.

Upvotes: 9

Anne
Anne

Reputation: 27073

Both dates are indeed slightly different. Quick example to show the difference:

NSDate *one = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSinceNow:4000000];

NSComparisonResult difference = [two compare:one];

NSLog(@"Date one: %@",one);
NSLog(@"Date two: %@",two);

NSLog(@"Exact difference: %ld",difference);

Output:

Date one: 2012-01-03 07:47:40 +0000
Date two: 2012-01-03 07:47:40 +0000
Exact difference: 1

EDIT

isEqualToDate: returns true in the following example:

NSDate *one = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
NSDate *two = [[NSDate alloc]initWithTimeIntervalSince1970:4000000];
if ([one isEqualToDate:two]) NSLog(@"Equal");

Output:

Equal

Upvotes: 5

Related Questions