【问题标题】:Date/Time comparison in rubyruby 中的日期/时间比较
【发布时间】:2014-09-27 13:19:07
【问题描述】:

我有这些日期和时间:

schedule.day_start    # => 2014-09-27 15:30:00 UTC
date_now = Time.now   # => 2014-09-27 15:11:14 +0200
date_now + 60.minutes # => 2014-09-27 16:11:14 +0200

我正在尝试检测在day_start 之前 60 分钟或更短时间开始的所有计划。使用以下代码,我得到的是"NO" 而不是"YES" 的响应。

if schedule.day_start < (Time.now + 60.minutes)
  "YES"
else
  "NO"
end

为什么2014-09-27 15:30:00 UTC2014-09-27 16:11:14 +0200 大?

【问题讨论】:

    标签: ruby-on-rails ruby date time comparison


    【解决方案1】:

    将日期设为 UTC,这样可以避免时区问题

    if schedule.day_start.utc < (Time.now + 60.minutes).utc
      ...
    

    【讨论】:

    • 感谢本杰明的留言。我试过了,但Time.now.utc 显示我2014-09-27 14:10:14 UTC,但当前时间是2014-09-27 16:10:14 UTC。那么如何比较这两个日期呢? (schedule.day_start 显示“正确”日期 - 不是 -2 hours
    • 在什么情况下你会得到Time.now?因为如果例如将它分配给一个常量或全局变量,它可能会记录您启动服务器的时间。还要检查您是否正确设置了config.time_zone,当然如果您的系统在正确的时间使用ntpdate
    【解决方案2】:

    因为

    2014-09-27 16:11:14 +0200
    

    同时

    2014-09-27 14:11:14 UTC
    

    先于

    2014-09-27 15:30:00 UTC
    

    对于Time 对象,“跟随”转换为“更大”。

    【讨论】:

    • 感谢 Sawa 的留言。但是请您解释一下,With Time objects, "follows" translates to "greater". 是什么意思?
    • 如果时间 A 在时间尺度上出现在(即跟随)时间 B 之后,那么 Ruby 中的代码 A &gt; B 将是 true(即A大于B)。
    【解决方案3】:

    任何地方,如果时间 A 在时间 B 之后,则认为 A 大于 B。你的情况也是如此。


    schedule.day_start # => 2014-09-27 15:30:00 UTC

    date_now + 60.minutes # => 2014-09-27 16:11:14 +0200 即 2014-09-27 14:11:14 UTC。

    在这里,您可以清楚地看到,Time.now + 60.minutes 是 schedule.day_start 之前的一个时间戳。因此,schedule.day_start 大于 Time.now + 60.minutes,这就是为什么您的 "if" 案例不成立,因此会打印 NO。 p>

    【讨论】:

      【解决方案4】:

      记住你的结果是 false 因为 GMT,要解决这个问题并使用 UTC 比较没有 GMT 的唯一日期时间,试试这个:

      minutes = 60.minutes 
      t1 = Time.at(schedule.day_start.utc).to_datetime
      t2 = Time.at((Time.now + minutes).utc).to_datetime
      
      if t1 < t2
        "YES"
      else
        "NO"
      end
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2013-09-21
        • 2012-01-20
        • 2023-03-08
        • 1970-01-01
        相关资源
        最近更新 更多