4

这是代码

NSDate* d = [NSDate dateWithTimeIntervalSince1970:32.4560];
double ti = [d timeIntervalSince1970];
NSLog(@"Interval: %f %f %f %f",ti,32.4560,ti*1000.0,32.4560*1000.0);

输出是

间隔:32.456000 32.456000 32455.999970 32456.000000

为什么 NSDate 返回失去一些精度的值?

4

1 回答 1

7

这不是问题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.
于 2010-12-16T05:36:22.307 回答