Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
422 views
in Technique[技术] by (71.8m points)

ruby on rails - Iterating between two DateTimes, with a one hour step

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.

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...