RoR, Can't iterate from DateTime/TimeWithZone

笑着哭i 提交于 2019-12-04 15:26:07

问题


I have a simple task where I want to take a starting date and an ending date and loop over the days/dates. This code is being used in my db:seed rake task. Currently, my code has gone through the following attempts.

(someModel.start_date.to_datetime..someModel.end_date.to_datetime).each { 
    |x| puts x 
}
 ......
(someModel.start_date...someModel.end_date).each { |x| puts x }

In each case, I get an error like this.

can't iterate from ActiveSupport::TimeWithZone
or 
can't iterate from DateTime

If anyone has any clue on how to iterate over a range of DateTimes I'd be greatly appreciative.


回答1:


start = someModel.start_date.to_datetime
finish = someModel.end_date.to_datetime
while(start < finish) do
  #bunch of awesome stuff
  start += 1.day
end



回答2:


You must make sure that you are dealing with a Date object (by calling to_date), then everything works as expected:

start_date.to_date.upto(end_date.to_date) {|date| puts date }

Or with a range:

(start_date.to_date..end_date.to_date).to_a



回答3:


You can't iterate from DateTime. But you can iterate when start and end of interval are instances of Date. Convert them if possible.

And then look at these Date methods:

  • step()
  • upto()
  • downto()

to use instead of each




回答4:


If you want to iterate on the range you might consider a loop and step each day using something like someModel.start_date + 1.day.to_i



来源:https://stackoverflow.com/questions/21744683/ror-cant-iterate-from-datetime-timewithzone

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!