I'm trying to step every N days between two dates. I tried the following code but is wasn't working because startDate and endDate are ActiveSupport::TimeWithZone objects and not DateTime objects like I thought.
startDate.step(endDate, step=7) { |d| puts d.to_s}
min.step(max, step=stepInt){ |d|
puts d.to_s
}
How do I covert the TimeWithZone object to a DateTime?
I thought it might be useful to update this answer as I was searching this up recently. The easiest way to achieve this conversion is using the .to_datetime() function.
e.g.
5.hours.from_now.class # => ActiveSupport::TimeWithZone
5.hours.from_now.to_datetime.class # => DateTime
ref: http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-to_datetime
DateTime
is an old class which you generally want to avoid using. Time
and Date
are the two you want to be using. ActiveSupport::TimeWithZone
acts like Time
.
For stepping over dates you probably want to deal with Date
objects. You can convert a Time
(or ActiveSupport::TimeWithZone
) into a Date
with Time#to_date
:
from.to_date.step(to.to_date, 7) { |d| puts d.to_s }
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With