Brig
Brig

Reputation: 10321

Convert ActiveSupport::TimeWithZone to DateTime

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?

Upvotes: 28

Views: 28593

Answers (2)

Chris James
Chris James

Reputation: 531

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

Upvotes: 41

Jason Weathered
Jason Weathered

Reputation: 7801

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 }

Upvotes: 20

Related Questions