Skip to content

Instantly share code, notes, and snippets.

@emmahsax
Last active March 16, 2024 18:47
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save emmahsax/af285a4b71d8506a1625a3e591dc993b to your computer and use it in GitHub Desktop.
Save emmahsax/af285a4b71d8506a1625a3e591dc993b to your computer and use it in GitHub Desktop.
Easily turn seconds into a human-readable time in Ruby

Turn Seconds into Human-Readable Time with Ruby

If you have an integer which is an amount of seconds, you can easily turn it into the form

X days, Y hours, Z minutes, Q seconds

Here's a little method that will do all of that!

def human_readable_time(secs)
  [[60, :seconds], [60, :minutes], [24, :hours], [Float::INFINITY, :days]].map do |count, name|
    next unless secs > 0

    secs, number = secs.divmod(count)
    "#{number.to_i} #{number == 1 ? name.to_s.delete_suffix('s') : name}" unless number.to_i == 0
  end.compact.reverse.join(', ')
end

> human_readable_time(1)
=> "1 second"
> human_readable_time(2)
=> "2 seconds"
> human_readable_time(60)
=> "1 minute"
> human_readable_time(120)
=> "2 minutes"
> human_readable_time(3600)
=> "1 hour"
> human_readable_time(7200)
=> "2 hours"
> human_readable_time(86400)
=> "1 day"
> human_readable_time(172800)
=> "2 days"
> human_readable_time(1872981)
=> "21 days, 16 hours, 16 minutes, 21 seconds"

Notice how the method is smart enough to detect when a unit should be pluralized or not ('1 day' versus '2 days').

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