从float转换的Ruby时间对象不等于orignial时间对象 [英] Ruby Time object converted from float doesn't equal to orignial Time object

查看:129
本文介绍了从float转换的Ruby时间对象不等于orignial时间对象的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

time = Time.now
fvalue = time.to_f
return time == Time.at(fvalue)

这里有人可以解释为什么上面的表达式返回false。如何从float中创建一个与时间变量匹配的新时间对象?

Can somebody here explain why the above expression returns false. How can I create a new Time object from float that matches the original time variable?

谢谢

推荐答案

IEEE 754 double (由 to_f )不够准确,无法代表确切时间。

IEEE 754 double (which is returned by to_f) is not accurate enough to represent the exact time.

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

执行以下操作以保留确切的时间:

Do the following, to preserve the exact time:

t1 = Time.now
r1 = t1.to_r # value of time as a rational number
t2 = Time.at(r1)
t1 == t2 #=> true

Time.to_r


此方法旨在用于获取表示自Epoch以来的纳秒的精确值
。您可以使用此方法
将时间转换为另一个纪元。

This methods is intended to be used to get an accurate value representing the nanoseconds since the Epoch. You can use this method to convert time to another Epoch.

这篇关于从float转换的Ruby时间对象不等于orignial时间对象的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆