Time difference in hours

前端 未结 7 1915
不知归路
不知归路 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.

    0 讨论(0)
  • 2020-12-04 16:45

    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
    
    0 讨论(0)
  • 2020-12-04 16:50

    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
    
    0 讨论(0)
  • 2020-12-04 16:53

    You can use a Rails' method distance_of_time_in_words

    distance_of_time_in_words(starting_time, ending_time, options = {include_seconds: true })
    
    0 讨论(0)
  • 2020-12-04 17:00

    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
    
    0 讨论(0)
  • 2020-12-04 17:01
    ((date_2 - date_1) / 3600).round
    

    or

    ((date_2 - date_1) / 1.hour).round
    
    0 讨论(0)
提交回复
热议问题