Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

RoR, Can't iterate from DateTime/TimeWithZone

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.

like image 574
Black Dynamite Avatar asked Feb 13 '14 03:02

Black Dynamite


2 Answers

start = someModel.start_date.to_datetime
finish = someModel.end_date.to_datetime
while(start < finish) do
  #bunch of awesome stuff
  start += 1.day
end
like image 189
Chris Barretto Avatar answered Nov 08 '22 10:11

Chris Barretto


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
like image 10
collimarco Avatar answered Nov 08 '22 09:11

collimarco