与ActiveSupport的时间比较失败

时间:2014-02-19 21:34:21

标签: ruby-on-rails ruby

now = Time.zone.now
=> Wed, 19 Feb 2014 21:30:56 UTC +00:00 
Time.zone.at(now.to_i)
=> Wed, 19 Feb 2014 21:30:56 UTC +00:00 
now == Time.zone.at(now.to_i)
=> false

怎么可能?

UPD:

Time.zone.at(now.to_i).to_i == now.to_i
=> true

1 个答案:

答案 0 :(得分:3)

Ruby跟踪时间到纳秒:

now = Time.zone.now
=> Wed, 19 Feb 2014 21:30:56 UTC +00:00 
Time.zone.at(now.to_f)
=> Wed, 19 Feb 2014 21:30:56 UTC +00:00 
now == Time.zone.at(now.to_f)
=> false

但是如果你比较纳秒,你会看到它们不一样,即使用float值创建时间对象,因为用于创建新时间对象的浮点值不如纳秒值那么准确。时间:

now.nsec
=> 956134961
Time.zone.at(now.to_f).nsec
=> 956134796