calculate difference in time in days, hours and mi

2020-03-25 18: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_time = Time.now.strftime('%Y-%m-%d %H:%M')
Time.diff(Time.parse('2011-08-12 09:00'), Time.parse(cur_time))

Thanks, Brett.

回答1:

I've used time_diff to achieve this sort of thing easily before, you may want to check it out.



回答2:

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]