从float转换的Ruby Time对象不等于orignial Time对象
time = Time.now fvalue = time.to_f return time == Time.at(fvalue)
有人可以在这里解释为什么上面的表达式返回false。 如何从float创建一个与原始时间变量匹配的新Time对象?
谢谢
IEEE 754 double (由to_f
返回)不够精确,无法表示准确的时间。
t1 = Time.now f1 = t1.to_f t2 = Time.at(f1) # they look the same t1.inspect #=> '2013-09-09 23:46:08 +0200' t2.inspect #=> '2013-09-09 23:46:08 +0200' # but double does not have enough precision to be accurate to the nanosecond t1.nsec #=> 827938306 t2.nsec #=> 827938318 # ^^ # so they are different t1 == t2 #=> false
执行以下操作以保留确切时间:
t1 = Time.now r1 = t1.to_r # value of time as a rational number t2 = Time.at(r1) t1 == t2 #=> true
Time.to_r
自Time.to_r
:
该方法旨在用于获得表示自Epoch以来纳秒的精确值。 您可以使用此方法将时间转换为另一个Epoch。