Dany
Dany

Reputation: 2800

How to iterate through hour from date time in ruby

In my use case I have to get the hours between two dates in ruby[Not rails]. For example hours between 2015-10-25T22:04:55Z to 2015-10-26T08:30:35Z should be

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

Range can be from different dates.There are few posts related to this but does not solve this.

Version : ruby 1.9

Could anyone help me on this?

Upvotes: 1

Views: 365

Answers (2)

kaspernj
kaspernj

Reputation: 1263

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]

Upvotes: 1

pangpang
pangpang

Reputation: 8821

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

Upvotes: 1

Related Questions