2011-11-18 86 views
2

我在学习如何将NSDate对象与isEqualToDateDate方法进行比较。我不明白为什么这个简单的测试不会返回true并打印出NSLog。在此先感谢比较两个NSDate对象不能正常工作

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

回答

9

我相信,这可能是错的,既然你是使用initWithTimeIntervalSinceNow的对象是在稍微不同的时间被分配,从而使他们不等。

+0

是的我想你可能是对的 - 我已经改变了方法initWithTimeIntervalSince1970,一切都很好。我没有得到的是这个方法是什么,如果它总是返回false。任何进一步的帮助将是伟大的。 – pete

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 

EDIT

isEqualToDate:返回true在下面的例子:

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

输出:

Equal 
+1

看http://developer.apple.com/library/mac/#documentation/Cocoa/Reference/Foundation/Miscellaneous/Foundation_Constants/Reference/reference.html#//apple_ref/c/tdef/NSComparisonResult 1意味着它是有序的降序 – vikingosegundo

+0

谢谢安妮,但他们的差异 - 他们打印出相同的! – pete

+0

它们以毫秒为单位 – vikingosegundo