Skip to content

Instantly share code, notes, and snippets.

Show Gist options
  • Save csanz/669588 to your computer and use it in GitHub Desktop.
Save csanz/669588 to your computer and use it in GitHub Desktop.
to generate a human readable time range using ruby on rails
def humanize secs
[[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].inject([]){ |s, (count, name)|
if secs > 0
secs, n = secs.divmod(count)
s.unshift "#{n.to_i} #{name}"
end
s
}.join(' ')
end
p humanize 1234
#=>"20 minutes 34 seconds"
p humanize 12345
#=>"3 hours 25 minutes 45 seconds"
p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"
p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"
@vishal-pandey
Copy link


def humanize secs
  [[60, :seconds], [60, :minutes], [24, :hours], [1000, :days]].inject([]){ |s, (count, name)|
    if secs > 0
      secs, n = secs.divmod(count)
      s.unshift "#{n.to_i} #{name}" if n.to_i > 0 # To avoid 0 minutes 0 seconds
    end
    s
  }.join(' ')
end

p humanize 1234
#=>"20 minutes 34 seconds"
p humanize 12345
#=>"3 hours 25 minutes 45 seconds"
p humanize 123456
#=>"1 days 10 hours 17 minutes 36 seconds"
p humanize(Time.now - Time.local(2010,11,5))
#=>"4 days 18 hours 24 minutes 7 seconds"


Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment