Can Ruby print out time difference (duration) readily?

Can Ruby do something like this?

irb(main):001:0> start = Time.now
=> Thu Nov 05 01:02:54 -0800 2009

irb(main):002:0> Time.now - start
=> 25.239

irb(main):003:0> (Time.now - start).duration
=> "25 seconds"

(the duration method doesn't exist now)... and similarly, report

23 minutes and 35 seconds
1 hour and 33 minutes
2 days and 3 hours

(either report the whole duration, up to how many seconds, or report up to 2 numbers and units (if day and hour is reported, then no need to tell how many minutes))


Here's a quick and simple way to implement this. Set predefined measurements for seconds, minutes, hours and days. Then depending on the size of the number, output the appropriate string with the those units. We'll extend Numeric so that you can invoke the method on any numeric class ( Fixnum , Bignum , or in your case Float ).

class Numeric
  def duration
    secs  = self.to_int
    mins  = secs / 60
    hours = mins / 60
    days  = hours / 24

    if days > 0
      "#{days} days and #{hours % 24} hours"
    elsif hours > 0
      "#{hours} hours and #{mins % 60} minutes"
    elsif mins > 0
      "#{mins} minutes and #{secs % 60} seconds"
    elsif secs >= 0
      "#{secs} seconds"
    end
  end
end

There is a gem available https://rubygems.org/gems/time_diff

Which gives the difference in a hash


为https://rubygems.org/gems/time_difference尝试使用ruby gem - Ruby文档的Time Difference gem,网址为https://github.com/tmlee/time_difference

start_time = Time.new(2013,1)
end_time = Time.new(2014,1)
TimeDifference.between(start_time, end_time).in_years
=> 1.0
链接地址: http://www.djcxy.com/p/17092.html

上一篇: 为什么特征类不等于self.class,看起来如此相似?

下一篇: Ruby可以随时打印时间差(持续时间)吗?