【问题标题】:tell if DateTime is within one hour of current time判断 DateTime 是否在当前时间的一小时内
【发布时间】:2016-08-12 13:20:44
【问题描述】:

如果dte 在当前时间的 1 小时内,我的目标是停止循环。有没有“红宝石方式”来做到这一点?

#THIS IS AN INFINITE LOOP, DONT RUN THIS
dte=DateTime.strptime("2000-01-01 21:00:00", '%Y-%m-%d %H:%M:%S')
while(dte<(DateTime.now.to_time-1).to_datetime)
    #increments dte by one hour, not shown here
end 

【问题讨论】:

    标签: ruby datetime


    【解决方案1】:

    纯 Ruby 方式(不包括 rails 的 active_support):

    您只需要休息一天。

    one_hour_ago_time = (DateTime.now - (1.0/24))
    
    • 1.0 = 一天
    • 1.0/24 = 1 小时
    • 1.0/(24*60) = 1 分钟
    • 1.0/(24*60*60) = 1 秒

    【讨论】:

      【解决方案2】:

      如果您确实需要使用 DateTime,那么您的做法是正确的。

      Subtract n hours from a DateTime in Ruby

      你也可以这样做:

      require 'time'
      time = Time.parse('2000-01-01 21:00:00')
      while time < Time.now - 3600 do
        ...
      end
      

      使用 active_support 核心扩展可以提高效率。

      require 'active_support/core_ext/numeric/time'    
      while time < Time.now - 1.hour do
        ...
      end
      

      更好

      while time < 1.hour.ago do
        ...
      end
      

      【讨论】:

        【解决方案3】:

        你也可以试试这个:

        current_time = DateTime.now.strftime("%Y-%m-%d %H:%M:%S")
        
        last_time = (DateTime.now - (1.0/24)).strftime("%Y-%m-%d %H:%M:%S")
        
        last_time.upto(current_time) {|date| puts date }
        

        【讨论】:

        • hour 方法在 ruby​​ 中不受支持,这是一个 Rails 方法
        • 使用require 'active_support' bcs。这将产生undefined method hour for 1:Fixnum
        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2010-12-02
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2023-04-05
        • 1970-01-01
        相关资源
        最近更新 更多