【问题标题】:How to iterate through hour from date time in ruby如何在ruby中从日期时间迭代小时
【发布时间】:2015-10-27 07:10:23
【问题描述】:

在我的用例中,我必须在 ruby​​ [不是 rails] 中获取两个日期之间的小时数。例如 2015-10-25T22:04:55Z 到 2015-10-26T08:30:35Z 之间的时间应该是

[2015-10-25-23, 2015-10-26-00, 2015-10-26-01, 2015-10-26-02, 2015-10-26-03, 2015-10-26-04, 2015-10-26-05, 2015-10-26-06, 2015-10-26-07, 2015-10-26-08]

范围可以来自不同的日期。与此相关的帖子很少,但不能解决此问题。

版本:红宝石 1.9

谁能帮我解决这个问题?

【问题讨论】:

    标签: ruby time range hour


    【解决方案1】:
    require 'date'
    a = DateTime.parse("2015-10-25T22:04:55Z")
    b = DateTime.parse("2015-10-26T08:30:35Z")
    
    ((b - a) * 24).to_i  # get the time difference 
    => 10
    
    a + 1 / 24.0 #get the next hour
    => #<DateTime: 2015-10-25T23:04:55+00:00 ((2457321j,83095s,0n),+0s,2299161j)>
    
    1.upto(((b - a) * 24).to_i).map{|e| (a + e / 24.0).strftime("%Y-%m-%d-%H")}
    => ["2015-10-25-23", "2015-10-26-00", "2015-10-26-01", "2015-10-26-02", "2015-10-26-03", "2015-10-26-04", "2015-10-26-05", "2015-10-26-06", "2015-10-26-07", "2015-10-26-08"]
    

    【讨论】:

    • 我是 ruby​​ 新手。如果我将它添加到一个函数中,它会添加很多重复项。我必须使用 set 吗?
    • @DineshAppavoo 我认为它没有重复项。如果有,你可以使用 uniq 方法。
    • 它不会在 irb 中显示重复项。但从文件运行时显示重复。 uniq 再次起作用了!
    【解决方案2】:
    require "date"
    
    date_from = DateTime.parse("2015-10-25 22:04:55").to_time
    date_to = DateTime.parse("2015-10-26 08:30:35").to_time
    date_current = date_from
    
    collection = []
    
    while date_current < date_to
      collection << date_current
      date_current += 3600 # 3600 seconds is a hour
    end
    
    collection #=> [2015-10-25 23:04:55 +0100, 2015-10-26 00:04:55 +0100, 2015-10-26 01:04:55 +0100, 2015-10-26 02:04:55 +0100, 2015-10-26 03:04:55 +0100, 2015-10-26 04:04:55 +0100, 2015-10-26 05:04:55 +0100, 2015-10-26 06:04:55 +0100, 2015-10-26 07:04:55 +0100, 2015-10-26 08:04:55 +0100, 2015-10-26 09:04:55 +0100]
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 2018-10-22
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2020-11-26
      • 2013-06-18
      相关资源
      最近更新 更多