如何使用ruby在rails上生成可读的时间范围

我试图找到生成以下输出的最佳方法

<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

有没有更有效的方法来做到这一点。 对于一些超级简单的东西来说,它似乎有很多冗余代码。

另一个用途是:

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

这个代码是相似的,但我使用Time.now:

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

如果你需要比distance_of_time_in_words更“精确”的东西,你可以写下这些内容:

def humanize secs
  [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].map{ |count, name|
    if secs > 0
      secs, n = secs.divmod(count)
      "#{n.to_i} #{name}"
    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"

哦,你的代码有一句话:

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

是真正的糟糕的方式来获得差异。 简单使用:

self.updated_at - self.created_at

DateHelper中有两种方法可能会给你你想要的:

  • time_ago_in_words

    time_ago_in_words( 1234.seconds.from_now ) #=> "21 minutes"
    
    time_ago_in_words( 12345.seconds.ago )     #=> "about 3 hours"
    
  • distance_of_time_in_words

    distance_of_time_in_words( Time.now, 1234.seconds.from_now ) #=> "21 minutes"
    
    distance_of_time_in_words( Time.now, 12345.seconds.ago )     #=> "about 3 hours"
    

  • chronic_duration将数字时间分析为可读,反之亦然

    链接地址: http://www.djcxy.com/p/95405.html

    上一篇: How to generate a human readable time range using ruby on rails

    下一篇: Jquery Accordion Close then Open