2 NSDates应该相等不是? [英] 2 NSDates that should be equal aren't?
问题描述
我使用的是Stig Brautaset的JSON库(http://code.google.com/p/json-framework),我需要序列化NSDate。我在考虑把它转换成一个字符串之前JSON化它,但是,我遇到了这种奇怪的行为:
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:
为什么这些NSDates被认为是相等的?
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!");
}
推荐答案
对象,您从原始对象中丢失了一些亚秒级的精度 - 换句话说, -description
会消失小数秒,并返回
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
国际格式的接收器的字符串表示
YYYY-MM-DD HH:MM:SS±HHMM
,其中±HHMM
表示以GMT和分钟为单位的时区偏移
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
当你根据描述创建一个新的日期对象时,你会得到它在整秒钟,因为字符串只精确到一整秒。因此 -isEqualToDate:
返回 NO
,因为
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.
此方法检测日期之间的次秒差异。如果您想比较不太细粒度的日期,请使用
timeIntervalSinceDate:
来比较这两个日期。
所以你可以这样做( NSTimeInterval
措施在几秒钟内):
So you'd do something like this instead (NSTimeInterval
measures in seconds):
if ([d timeIntervalSinceDate:dd] == 0) {
NSLog(@"Yay!");
}
这篇关于2 NSDates应该相等不是?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!