Convert seconds to hours:minutes:seconds in Ruby

Today I was working on an analytics report where the time a user spent on the site was being reported in seconds. I wanted to convert this into a nicer format – hours:minutes:seconds. I had hoped that there was a nice helper in Rails to accomplish this, but unfortunately there isn’t.

Luckily simple math can still help us here – this is what I came up with.

def seconds_to_time(seconds)
  [seconds / 3600, seconds / 60 % 60, seconds % 60].map { |t| t.to_s.rjust(2,'0') }.join(':')

Happy coding.