在Ruby中比较时间的正确方法是什么?

时间:2013-01-09 05:34:03

标签: ruby-on-rails ruby datetime

以下示例让我感到困惑。为什么比较返回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

我做错了什么?

1 个答案:

答案 0 :(得分: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