下面的例子让我很困惑。为什么比较返回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
我做错了什么?
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