Iterating between two DateTimes, with a one hour step

前端 未结 4 2137
轻奢々
轻奢々 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 06:51

    Similar to my answer in "How do I return an array of days and hours from a range?", the trick is to use to_i to work with seconds since the epoch:

    ('2013-01-01'.to_datetime.to_i .. '2013-02-01'.to_datetime.to_i).step(1.hour) do |date|
      puts Time.at(date)
    end
    

    Note that Time.at() converts using your local time zone, so you may want to specify UTC by using Time.at(date).utc

提交回复
热议问题