Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Time comparison with ActiveSupport failed

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

How is it possible?

Upd:

Time.zone.at(now.to_i).to_i == now.to_i
=> true
like image 705
freemanoid Avatar asked Feb 19 '14 21:02

freemanoid


1 Answers

Ruby tracks time down to the nanosecond:

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

But if you compare the nanoseconds, you will see they are not the same, even when creating the time object using the float value, because the float value used to create the new time object is not as accurate as the nanosecond value of the time:

now.nsec
=> 956134961
Time.zone.at(now.to_f).nsec
=> 956134796
like image 159
jvperrin Avatar answered Sep 28 '22 04:09

jvperrin