Register now and start sharing your code snippets.
-->

Time ago in words (minutes, hours, days, weeks, months ago in words)

Ruby posted 4 months ago by christian

   1  def minutes_in_words(timestamp)
   2      minutes = (((Time.now - timestamp).abs)/60).round
   3      
   4      return nil if minutes < 0
   5      
   6      case minutes
   7        when 0..4            then '&lt; 5 minutes'
   8        when 5..14           then '&lt; 15 minutes'
   9        when 15..29          then '&lt; 30 minutes'
  10        when 30..59          then '&gt; 30 minutes'
  11        when 60..119         then '&gt; 1 hour'
  12        when 120..239        then '&gt; 2 hours'
  13        when 240..479        then '&gt; 4 hours'
  14        when 480..719        then '&gt; 8 hours'
  15        when 720..1439       then '&gt; 12 hours'
  16        when 1440..11519     then '&gt; ' << pluralize((minutes/1440).floor, 'day')
  17        when 11520..43199    then '&gt; ' << pluralize((minutes/11520).floor, 'week')
  18        when 43200..525599   then '&gt; ' << pluralize((minutes/43200).floor, 'month')  
  19        else                      '&gt; ' << pluralize((minutes/525600).floor, 'år')
  20      end
  21    end

There are also similar implementations:
  1. http://www.actsasflinn.com/articles/2007/04/10/time-ago-method-for-ruby-on-rails
  2. http://timeago.yarp.com/
Tagged month, week, hour, minutes, words, rails, ruby