如何在 ruby​​ 中比较时间 [英] How to compare Time in ruby

查看:41
本文介绍了如何在 ruby​​ 中比较时间的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我需要使用 Time 对象作为 int (TimeObject.to_i)然后我需要将 int 转换回时间,以与原始时间进行比较.简短示例

I need to use a Time object as a int (TimeObject.to_i) Then i need to convert a int back to a Time, to compare against the original Time. Short Example

t1 = Time.now
t2 = Time.at(t1.to_i)
puts t1 == t2    # Says False
puts t1.eql?(t2) # Says False

为什么这说它是假的?当我打印两个 Time objetcs 显示相同的东西 D:

Why this says its false ? When i print both Time objetcs shows the same thing 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 进行比较时?说他们不同(抱歉我的英语不好)

they are the same thing D: but when trying to compare with == or eql? says they are diferent (sorry for my bad english)

推荐答案

答案

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

说明:

如果 time 和 other_time 都是具有相同秒数和小数秒的 Time 对象,则返回 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 时会丢失几分之一秒,然后恢复的时间与原始时间不完全相同.但是如果我们恢复两个副本,它们就会相等.

So, apparently, fractions of seconds get dropped when performing #to_i and then restored time is not exactly the same as original one. But if we restore two copies, they will be equal.

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

One may think, "Hey, let's use #to_f then!". But, surprisingly enough, results are the same! Maybe it's because of rounding errors or floating point comparison, not sure.

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

Don't convert integer back to time for comparison. Convert original time to int instead!

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​​ 中比较时间的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆