问题
I'm using the JSON library from Stig Brautaset(http://code.google.com/p/json-framework) and I need to serialize an NSDate. I was considering converting it into a string before JSONifying it, however, I ran into this weird behavior:
Why aren't these NSDates considered equal?
NSDate *d = [[NSDate alloc] init];
NSDate *dd = [NSDate dateWithString:[d description]];
NSLog(@"%@", d);
NSLog(@"%@", dd);
if( [d isEqualToDate:dd] ){
NSLog(@"Yay!");
}
回答1:
When you describe the original date object you lose some sub-second precision from the original object — in other words, -description shaves off fractional seconds, and returns
A string representation of the receiver in the international format
YYYY-MM-DD HH:MM:SS ±HHMM
, where±HHMM
represents the time zone offset in hours and minutes from GMT
When you create a new date object based on the description, you get it in whole seconds because the string is only precise to a whole second. So -isEqualToDate: returns NO
because there is a difference of a fraction of a second between your two date objects, which it's sensitive to.
This method detects sub-second differences between dates. If you want to compare dates with a less fine granularity, use
timeIntervalSinceDate:
to compare the two dates.
So you'd do something like this instead (NSTimeInterval
measures in seconds):
if ([d timeIntervalSinceDate:dd] == 0) {
NSLog(@"Yay!");
}
回答2:
isEqualToDate detects subseconds differences between dates, but the description method does not include subseconds.
回答3:
Because they're not equivalent:
NSDate *d = [NSDate date];
NSDate *dd = [NSDate dateWithString:[d description]];
NSLog(@"%f", [d timeIntervalSinceReferenceDate]);
NSLog(@"%f", [dd timeIntervalSinceReferenceDate]);
Produces:
2011-04-28 11:58:11.873 EmptyFoundation[508:903] 325709891.867788
2011-04-28 11:58:11.874 EmptyFoundation[508:903] 325709891.000000
In other words, the +dateWithString:
method does not maintain sub-second precision.
来源:https://stackoverflow.com/questions/5823486/2-nsdates-that-should-be-equal-arent