我需要将时间对象用作 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
为什么说它是假的? 当我打印两个 Time 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, 1, 2012, 5, 6, true, "CLST"]
puts t2.to_a.to_s #shows : [ 53, 1, 16, 6, 1, 2012, 5, 6, true, "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
吧!”。但是,令人惊讶的是,结果是一样的!可能是因为舍入错误或 float 比较,不确定。
备选答案
不要将整数转换回时间进行比较。将原始时间转换为 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
关于ruby - 如何比较 ruby 中的时间,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/8763050/