/ Published in: Rails
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. ;)
Expand |
Embed | Plain Text
Copy this code and paste it in your HTML
def time_spent_in_words seconds, params={} time_periods_shown = params[:time_periods_shown] || 3 use_short_names = params[:use_short_names] || false return "0 seconds" if seconds < 1 short_name = {:second => :sec, :minute => :min, :hour => :hr, :day => :day, :week => :wk, :year => :yr} [[60, :second], [60, :minute], [24, :hour], [7, :day], [52, :week], [1000, :year]].map{ |count, name| if seconds > 0 seconds, n = seconds.divmod(count) name = short_name[name] if use_short_names "#{n.to_i} #{name}".pluralize(n.to_i) if n.to_i > 0 end }.compact.last(time_periods_shown).reverse.join(' ') end