How to generate a human readable time range using ruby on rails How to generate a human readable time range using ruby on rails ruby ruby

How to generate a human readable time range using ruby on rails


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(' ')endp 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


There are two methods in DateHelper that might give you what you want:

  1. time_ago_in_words

    time_ago_in_words( 1234.seconds.from_now ) #=> "21 minutes"time_ago_in_words( 12345.seconds.ago )     #=> "about 3 hours"
  2. 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 parses numeric time to readable and vice versa