Time difference in hours

2019-01-13 05:23发布

I am trying to get the difference in hours for two different Time instances. I get these values from the DB as a :datetime column

How can I do this so that it includes the months and years as well in the calculation while ignoring or rounding the minutes? Can this only be done manually or is there a function to do this?

标签: ruby time
6条回答
三岁会撩人
2楼-- · 2019-01-13 05:37

You can use a Rails' method distance_of_time_in_words

distance_of_time_in_words(starting_time, ending_time, options = {include_seconds: true })
查看更多
该账号已被封号
3楼-- · 2019-01-13 05:41
((date_2 - date_1) / 3600).round

or

((date_2 - date_1) / 1.hour).round
查看更多
爷的心禁止访问
4楼-- · 2019-01-13 05:43

You can use a gem called time_diff to get the time difference in very useful formats

查看更多
祖国的老花朵
5楼-- · 2019-01-13 05:45

this works great, example for number of hours since user created account

(Time.parse(DateTime.now.to_s) - Time.parse(current_user.created_at.to_s))/3600
查看更多
聊天终结者
6楼-- · 2019-01-13 05:53

In Rails, there is now a far more natural way to achieve this:

> past = Time.now.beginning_of_year
2018-01-01 00:00:00 +0100

> (Time.now - past) / 1.day
219.50031326506948
查看更多
劳资没心,怎么记你
7楼-- · 2019-01-13 05:55

Try Time Difference gem for Ruby at https://rubygems.org/gems/time_difference

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_years
查看更多
登录 后发表回答