2 个 NSDate 应该相等不是吗?
我正在使用 Stig Brautaset(http://code.google.com/p/json-framework) 的 JSON 库,我需要序列化 NSDate。我正在考虑在将其 JSON化之前将其转换为字符串,但是,我遇到了这种奇怪的行为:
为什么这些 NSDates 不被认为是相等的?
NSDate *d = [[NSDate alloc] init];
NSDate *dd = [NSDate dateWithString:[d description]];
NSLog(@"%@", d);
NSLog(@"%@", dd);
if( [d isEqualToDate:dd] ){
NSLog(@"Yay!");
}
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!");
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
当您描述原始日期对象时,您会失去原始对象的一些亚秒精度 - 换句话说,
-description
剃须关闭小数秒,然后返回当您根据描述创建新的日期对象时,您会在整秒内获得它,因为该字符串仅精确到整秒。所以
-isEqualToDate:
返回NO
因为存在分数差异两个日期对象之间的一秒,它对此很敏感。所以你应该这样做(
NSTimeInterval
以秒为单位):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 returnsWhen 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:
returnsNO
because there is a difference of a fraction of a second between your two date objects, which it's sensitive to.So you'd do something like this instead (
NSTimeInterval
measures in seconds):isEqualToDate 检测日期之间的亚秒差异,但描述方法不包括亚秒。
isEqualToDate detects subseconds differences between dates, but the description method does not include subseconds.
因为它们不等价:
产生:
换句话说,
+dateWithString:
方法不保持亚秒精度。Because they're not equivalent:
Produces:
In other words, the
+dateWithString:
method does not maintain sub-second precision.