微信公众号搜"智元新知"关注
微信扫一扫可直接关注哦!

如何比较ruby的时间

我需要使用Time对象作为int(TimeObject.to_i)
然后我需要将一个int转换回一个时间,以与原始时间进行比较.
简短的例子
t1 = Time.Now
t2 = Time.at(t1.to_i)
puts t1 == t2    # Says False
puts t1.eql?(t2) # Says False

为什么这说错呢?
当我同时打印时,objetcs显示同样的事情D:

puts t1                 #shows : 2012-01-06 16:01:53 -0300
puts t2                 #shows : 2012-01-06 16:01:53 -0300
puts t1.to_a.to_s       #shows : [ 53,1,16,6,2012,5,true,"CLST"]      
puts t2.to_a.to_s       #shows : [ 53,"CLST"]

它们是同一件事D:但是当试图与==或eql进行比较时?说他们是不同的
(对不起,我的英语不好)

解决方法

回答
t1 = Time.Now
t2 = Time.at(t1.to_i)
t3 = Time.at(t1.to_i)
puts t1  # 2012-01-06 23:09:41 +0400
puts t2  # 2012-01-06 23:09:41 +0400
puts t3  # 2012-01-06 23:09:41 +0400

puts t1 == t2      # false
puts t1.equal?(t2) # false
puts t1.eql?(t2)   # false

puts t2.equal? t3  # false
puts t2.eql? t3    # true
puts t2 == t3      # true

说明:

eql?(other_time)

Return true if time and other_time are both Time objects with the same seconds and fractional seconds.

链接Time#eql?

因此,显然,执行#to_i时会丢弃几分之一秒,然后恢复时间与原始时间不完全相同.但如果我们恢复两份,他们将是平等的.

有人可能会想,“嘿,让我们再使用#to_f!”.但是,令人惊讶的是,结果是一样的!也许这是因为舍入错误或浮点比较,不确定.

替代答案

不要将整数转换回时间进行比较.将原始时间转换为int而不是!

t1 = Time.Now
t2 = Time.at(t1.to_i)

puts t1  # 2012-01-06 23:44:06 +0400
puts t2  # 2012-01-06 23:44:06 +0400

t1int,t2int = t1.to_i,t2.to_i

puts t1int == t2int           # true
puts t1int.equal?(t2int.to_i) # true
puts t1int.eql?(t2int)        # true

版权声明:本文内容由互联网用户自发贡献,该文观点与技术仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌侵权/违法违规的内容, 请发送邮件至 dio@foxmail.com 举报,一经查实,本站将立刻删除。

相关推荐