0

下面的例子让我很困惑。为什么比较返回false?

require 'active_support/time'

time1 = Time.new.utc.end_of_day  # 2013-01-09 23:59:59 UTC
time2 = Time.parse(time1.to_s)   # 2013-01-09 23:59:59 UTC

time1 == time2                   # false
time1.eql?(time2)                # false 
time1.equal?(time2)              # false

我究竟做错了什么?

4

1 回答 1

1

time2是从time1缺少信息的字符串表示生成的。即,微秒。

require 'active_support/time'

time1 = Time.new.utc.end_of_day  # => 2013-01-09 23:59:59 UTC
time2 = Time.parse(time1.to_s)   # => 2013-01-09 23:59:59 UTC

time1.usec # => 999999
time2.usec # => 0

解决方法:

如果您不需要微秒精度,则可以将两个时间戳都舍入到秒。

time1.to_i == time2.to_i # => true
于 2013-01-09T05:37:52.370 回答