Search code examples
ruby-on-railsrubyruby-on-rails-3ruby-on-rails-3.1

Iterate over Time in ruby


I am working on business analytics application, where I need to fetch some data on per hour basis of a particular month. for example I wanna get the data from jun 01 2012 to jun 30 2012 and I need to fetch the data of every hour between those days. Like 12:00 13:00,13:00-14:00 ....etc.

How do I do it. Kindly let me know. Using 1.8.7 platform.


Solution

  • If you are using Rails there is a Date method step: http://corelib.rubyonrails.org/classes/Date.html#M001273


    On pure ruby just write simple loop:

    t=Time.new(2012,01,01,0,0,0) #start time
    max_time=Time.new(2012,01,31,23,59,59) #end time
    step=60*60 #1hour
    while t<=max_time
         p t #your code here
         t += step
    end
    

    To simplify use this ruby extension:

    module TimeStep
    
      def step(limit, step)  # :yield: time
        t = self
        op = [:-,:<=,:>=][step<=>0]
        while t.__send__(op, limit)
           yield t
           t += step
        end
        self
      end
    end
    
    Time.send(:include, TimeStep) #include the extension
    

    Usage:

    t=Time.new(2012,01,01,0,0,0)
    t.step(Time.new(2012,01,31,23,59,59),3600) do |time|
      puts time
    end
    

    You can also down-iterate:

    t=Time.new(2012,01,31)
    t.step(Time.new(2012,01,1),-3600) do |time|
       puts time
    end