Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 377
Brig Avatar asked Dec 20 '10 23:12

Brig


2 Answers

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

like image 197
Chris A James Avatar answered Nov 11 '22 12:11

Chris A James


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 }
like image 30
Jason Weathered Avatar answered Nov 11 '22 13:11

Jason Weathered