calculate difference in time in days, hours and minutes

后端 未结 2 610
佛祖请我去吃肉
佛祖请我去吃肉 2021-01-14 12:35

UPDATE: I am updating the question to reflect the full solution. Using the time_diff gem Brett mentioned below, the following code worked.

code:

cur_         


        
2条回答
  •  逝去的感伤
    2021-01-14 13:31

    Without using a external gem, you can easily get differences between dates using a method like this:

    def release(time)
      delta = time - Time.now
    
      %w[days hours minutes].collect do |step|
        seconds = 1.send(step)
        (delta / seconds).to_i.tap do
          delta %= seconds
        end
      end
    end
    
    release(("2011-08-12 09:00:00").to_time)
    # => [7, 17, 37]
    

    which will return an array of days, hours and minutes and can be easily extended to include years, month and seconds as well:

    def release(time)
      delta = time - Time.now
    
      %w[years months days hours minutes seconds].collect do |step|
        seconds = 1.send(step)
        (delta / seconds).to_i.tap do
          delta %= seconds
        end
      end
    end
    
    release(("2011-08-12 09:00:00").to_time)
    # => [0, 0, 7, 17, 38, 13]
    

提交回复
热议问题