3

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!");
}

3 Answers 3

13

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
  • -timeIntervalSinceDate: was returning non-zero when my two dates were apparently 0.0005 seconds apart. I ended up comparing [NSString stringWithFormat:@"%.3f", d] for each date.
    – Dov
    Jan 27, 2012 at 14:04
  • NSDate.timeIntervalSinceDate return an NSTimeInterval which is a Double value which may be smaller as a second. I this case i suggest to check like this `[d timeIntervalSinceDate:dd] < 1' If 1 seconed to vague us a smaller number e.g. 0.1
    – Stephan
    Jul 23, 2015 at 18:50
2

isEqualToDate detects subseconds differences between dates, but the description method does not include subseconds.

2

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.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.