将ActiveSupport :: TimeWithZone转换为DateTime

Bri*_*rig 20 ruby datetime ruby-on-rails

我想在两个日期之间每N天步一次.我尝试了下面的代码,但是因为startDate和endDate是ActiveSupport :: TimeWithZone对象而不是像我想的那样是DateTime对象.

startDate.step(endDate, step=7) { |d| puts d.to_s}
  min.step(max, step=stepInt){ |d|
  puts d.to_s  
}
Run Code Online (Sandbox Code Playgroud)

如何将TimeWithZone对象转换为DateTime?

小智 32

我认为在我最近搜索这个答案时更新这个答案可能会有用.实现此转换的最简单方法是使用.to_datetime()函数.

例如

5.hours.from_now.class              # => ActiveSupport::TimeWithZone
5.hours.from_now.to_datetime.class  # => DateTime
Run Code Online (Sandbox Code Playgroud)

参考:http://api.rubyonrails.org/classes/ActiveSupport/TimeWithZone.html#method-i-to_datetime


Jas*_*red 15

DateTime是一个你通常想避免使用的旧类.Time并且Date是你想要使用的两个.ActiveSupport::TimeWithZone表现得像Time.

对于踩过日期,您可能想要处理Date对象.你可以转换Time(或ActiveSupport::TimeWithZone)成Date具有Time#to_date:

from.to_date.step(to.to_date, 7) { |d| puts d.to_s }
Run Code Online (Sandbox Code Playgroud)

  • DateTime是一个Ruby类.ActiveSupport :: TimeWithZones是Rails.所以说它是"老"而你应该避免它,这是不准确的.请参阅ChrisJ的回答以获得更好的回应. (15认同)
  • http://stackoverflow.com/questions/1261329/whats-the-difference-between-datetime-and-time-in-ruby建议将DateTime作为处理日期的最佳方式! (6认同)