rubytimerangehour

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?


Solution

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