2 NSDates that should be equal aren't?

不羁的心 提交于 2019-12-03 20:10:15

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

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

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!