如何在ruby中从日期时间迭代小时

vulvrdjw  于 2023-04-20  发布在  Ruby
关注(0)|答案(2)|浏览(77)

在我的用例中,我必须在ruby[Not rails]中获取两个日期之间的小时数。例如,2015-10- 25 T22:04:55 Z到2015-10- 26 T08:30:35 Z之间的小时数应该是
[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 1.9
有人能帮我吗?

vatpfxk5

vatpfxk51#

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"]
dfty9e19

dfty9e192#

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 an 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]

相关问题