如何使用 ruby​​ on rails 生成人类可读的时间范围

问题描述:

我正在尝试寻找生成以下输出的最佳方法

I'm trying to find the best way to generate the following output

<name> job took 30 seconds
<name> job took 1 minute and 20 seconds
<name> job took 30 minutes and 1 second
<name> job took 3 hours and 2 minutes

我开始这段代码

def time_range_details
  time = (self.created_at..self.updated_at).count
  sync_time = case time 
    when 0..60 then "#{time} secs"       
    else "#{time/60} minunte(s) and #{time-min*60} seconds"
  end
end

有没有更有效的方法来做到这一点.对于超级简单的事情来说,似乎有很多冗余代码.

Is there a more efficient way of doing this. It seems like a lot of redundant code for something super simple.

另一个用途是:

<title> was posted 20 seconds ago
<title> was posted 2 hours ago

此代码类似,但我使用 Time.now:

The code for this is similar, but instead i use Time.now:

def time_since_posted
  time = (self.created_at..Time.now).count
  ...
  ...
end

如果您需要比 distance_of_time_in_words,您可以按照以下方式编写:

If you need something more "precise" than distance_of_time_in_words, you can write something along these lines:

def humanize secs
  [[60, :seconds], [60, :minutes], [24, :hours], [Float::INFINITY, :days]].map{ |count, name|
    if secs > 0
      secs, n = secs.divmod(count)

      "#{n.to_i} #{name}" unless n.to_i==0
    end
  }.compact.reverse.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"
p humanize 12345
#=>"3 hours 25 minutes 45 seconds"
p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"
p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"

哦,对你的代码有一句话:

Oh, one remark on your code:

(self.created_at..self.updated_at).count

真的是获得差异的糟糕方法.简单使用:

is really bad way to get the difference. Use simply:

self.updated_at - self.created_at