Skip to content

Instantly share code, notes, and snippets.

@pjho
Created October 8, 2014 19:53
Show Gist options
  • Save pjho/bccdb3aa38f2e112499c to your computer and use it in GitHub Desktop.
Save pjho/bccdb3aa38f2e112499c to your computer and use it in GitHub Desktop.
Rails - Convert Seconds to readable time - time_spent_in_words
# Source: http://snipplr.com/view/73984/human-readable-time-from-seconds-helper/
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
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment