Created
March 28, 2023 17:38
-
-
Save DevGW/49e5d6c712dc981d57e3fab5227efd48 to your computer and use it in GitHub Desktop.
Humanize time (seconds) #RoR #ruby
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
def humanize(secs) | |
[[60, :seconds], [60, :minutes], [24, :hours], [Float::INFINITY, :days]].map{ |count, name| | |
if secs > 0 | |
secs, n = secs.divmod(count) | |
"#{n.to_i} #{name}" unless n.to_i==0 | |
end | |
}.compact.reverse.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