比较两个不起作用的NSDate对象

时间:2011-11-18 00:27:55

标签: objective-c cocoa

我正在学习如何将NSDate个对象与isEqualToDateDate方法进行比较。我不明白为什么这个简单的测试不会返回true并打印出NSLog。提前致谢

#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;
}

2 个答案:

答案 0 :(得分:9)

我相信,这可能是错误的,因为您使用initWithTimeIntervalSinceNow表示在稍微不同的时间分配对象,从而使它们不相等。

答案 1 :(得分:5)

两个日期确实略有不同。显示差异的快速示例:

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

输出:

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

修改

isEqualToDate:在以下示例中返回true

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

输出:

Equal