Skip to content

Instantly share code, notes, and snippets.

@eljojo
Created June 24, 2013 14:15
Show Gist options
  • Star 2 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save eljojo/5850360 to your computer and use it in GitHub Desktop.
Save eljojo/5850360 to your computer and use it in GitHub Desktop.
How to generate a human readable time range using ruby on rails
# modification of http://stackoverflow.com/questions/4136248/how-to-generate-a-human-readable-time-range-using-ruby-on-rails
def humanize_seconds secs, precision = 2
return unless secs
units = [[60, :second], [60, :minute], [24, :hour], [1000, :day]]
diffs = units.map do |count, name|
next if units.find_index([count, name]) > precision
if secs > 0
secs, n = secs.divmod(count)
pluralize(n.to_i, name.to_s) if n > 0
end
end.compact.reverse
diffs = diffs[0 .. precision - 1] if precision
diffs.to_sentence
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment