这不是问题NSDate
本身。这是浮点数本身的性质。我相信NSDate
它的日期来自 OS X 时代(2001),而不是 UNIX 时代(1970)。让两个时期的差异为x。
然后发生的事情是这样的:
NSDate* d = [NSDate dateWithTimeIntervalSince1970:32.4560];
// at this point, d keeps 32.4560 + x
double ti = [d timeIntervalSince1970];
// ti is then (32.4560+x)-x
但是,浮点数没有无限精度。所以,+x
然后-x
可以在计算中引入轻微的误差。
有关更多信息,请阅读例如此 Wikipedia 文章。
如果你使用 OS X 时代,你会得到你天真期望的东西:
NSDate* d = [NSDate dateWithTimeIntervalSinceReferenceDate:32.4560];
// at this point, d keeps 32.4560 + 0
double ti = [d timeIntervalSinceReferenceDate];
// ti is then (32.4560+0)-0, which is 32.4560 even in the floating point world.