Time difference in hours

前端 未结 7 1961
不知归路
不知归路 2020-12-04 16:27

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 inclu

7条回答
  •  半阙折子戏
    2020-12-04 16:43

    in_hours (Rails 6.1+)

    Rails 6.1 introduces new ActiveSupport::Duration conversion methods like in_seconds, in_minutes, in_hours, in_days, in_weeks, in_months, and in_years.

    As a result, now, your problem can be solved as:

    date_1 = Time.parse('2020-10-19 00:00:00 UTC')
    date_2 = Time.parse('2020-10-19 03:35:38 UTC') 
    
    (date_2 - date_1).seconds.in_hours.to_i
    # => 3
    

    Here is a link to the corresponding PR.

提交回复
热议问题