human readable time from seconds (helper)


/ Published in: Rails
Save to your folder(s)

A very concise ruby on rails helper method that converts seconds into human readable format. It will not display any time periods that have 0 (ie: 1 hour 13 seconds - skipping minutes as there were none) Due to complexity, months were not factored into this converter, the function will go from weeks to years. I welcome anyone that feels the urge to fork this with month's included. ;)


Copy this code and paste it in your HTML
  1. def time_spent_in_words seconds, params={}
  2. time_periods_shown = params[:time_periods_shown] || 3
  3. use_short_names = params[:use_short_names] || false
  4.  
  5. return "0 seconds" if seconds < 1
  6. short_name = {:second => :sec, :minute => :min, :hour => :hr, :day => :day, :week => :wk, :year => :yr}
  7. [[60, :second], [60, :minute], [24, :hour], [7, :day], [52, :week], [1000, :year]].map{ |count, name|
  8. if seconds > 0
  9. seconds, n = seconds.divmod(count)
  10. name = short_name[name] if use_short_names
  11. "#{n.to_i} #{name}".pluralize(n.to_i) if n.to_i > 0
  12. end
  13. }.compact.last(time_periods_shown).reverse.join(' ')
  14. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.