开发者

calculate difference in time in days, hours and minutes

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-开发者_如何学Python12 09:00'), Time.parse(cur_time))

Thanks, Brett.


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]


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

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜