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 .. '2013-02-01'.to_datetime).step(1.hour) do |date|
...
end
I understand that an issue with this is that 1.hour is just the number of seconds, but my attempts to convert that to a DateTime object and use that as the step doesn’t work either.
I looked at “Beware of Ruby Sugar“. It mentions, near the bottom, that DateTime has a direct step method. I confirmed this by running methods on a DateTime object, but I cannot find any documentation on step in DateTime, in either Ruby’s or Rails’ documents.
Similar to my answer in “How do I return an array of days and hours from a range?“, the trick is to use
to_ito work with seconds since the epoch:Note that
Time.at()converts using your local time zone, so you may want to specify UTC by usingTime.at(date).utc