加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

如何比较ruby的时间

发布时间:2020-12-16 19:15:30 所属栏目:百科 来源:网络整理
导读:我需要使用Time对象作为int(TimeObject.to_i) 然后我需要将一个int转换回一个时间,以与原始时间进行比较. 简短的例子 t1 = Time.nowt2 = Time.at(t1.to_i)puts t1 == t2 # Says Falseputs t1.eql?(t2) # Says False 为什么这说错呢? 当我同时打印时,objetcs
我需要使用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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读