如何从 ruby 中的日期时间开始遍历小时
How to iterate through hour from date time in ruby
在我的用例中,我必须在 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]
范围可以不同dates.There与此相关的帖子很少,但没有解决这个问题。
版本:ruby1.9
谁能帮我解决这个问题?
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"]
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]
在我的用例中,我必须在 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]
范围可以不同dates.There与此相关的帖子很少,但没有解决这个问题。
版本:ruby1.9
谁能帮我解决这个问题?
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"]
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]