时间差

我试图得到两个不同的时间实例的小时差异。 我从数据库中获取这些值作为:datetime列

我怎样才能做到这一点,以便在计算中包括月份和年份,而忽略或舍入分钟? 这只能手动完成,或者有一个function来做到这一点?

((date_2 - date_1) / 3600).round 

要么

 ((date_2 - date_1) / 1.hour).round 

https://rubygems.org/gems/time_difference上试试Ruby的时间差异gem

 start_time = Time.new(2013,1) end_time = Time.new(2014,1) TimeDifference.between(start_time, end_time).in_years 

这个工程很好,例如自用户创build账户以来的小时数

 (Time.parse(DateTime.now.to_s) - Time.parse(current_user.created_at.to_s))/3600 

您可以使用称为time_diff的gem以非常有用的格式获取时差

你可以使用Rails的方法distance_of_time_in_words

 distance_of_time_in_words(starting_time, ending_time, options = {include_seconds: true })