Iterating between two DateTimes, with a one hour step

前端 未结 4 2147
轻奢々
轻奢々 2020-12-13 06:40

I\'m looking for an efficient way, in Ruby 1.9.x/Rails 3.2.x, to iterate between two DateTime objects, with a one-hour step.

(\'2013-01-01\'.to_datetime .. \         


        
4条回答
  •  粉色の甜心
    2020-12-13 07:13

    Maybe late but, you can do it without Rails, for example to step with hours:

    Ruby 2.1.0

    require 'time' 
    
    hour_step = (1.to_f/24)
    
    date_time = DateTime.new(2015,4,1,00,00)
    date_time_limit = DateTime.new(2015,4,1,6,00)
    
    date_time.step(date_time_limit,hour_step).each{|e| puts e}
    
    2015-04-01T00:00:00+00:00
    2015-04-01T01:00:00+00:00
    2015-04-01T02:00:00+00:00
    2015-04-01T03:00:00+00:00
    2015-04-01T04:00:00+00:00
    2015-04-01T05:00:00+00:00
    2015-04-01T06:00:00+00:00
    

    Or minutes:

    #one_minute_step = (1.to_f/24/60)
    
    fifteen_minutes_step = (1.to_f/24/4)
    
    date_time = DateTime.new(2015,4,1,00,00)
    date_time_limit = DateTime.new(2015,4,1,00,59)
    
    date_time.step(date_time_limit,fifteen_minutes_step).each{|e| puts e}
    
    2015-04-01T00:00:00+00:00
    2015-04-01T00:15:00+00:00
    2015-04-01T00:30:00+00:00
    2015-04-01T00:45:00+00:00
    

    I hope it helps.

提交回复
热议问题