Convert Seconds to Human Readable time (up to days)


/ Published in: Ruby
Save to your folder(s)

Pass in seconds and get back the amount of time in human readable format! ie: puts Utils.seconds_to_string(129) :=> 2 minutes, 9 seconds


Copy this code and paste it in your HTML
  1. class Utils
  2.  
  3. def self.seconds_to_string(s)
  4.  
  5. # d = days, h = hours, m = minutes, s = seconds
  6. m = (s / 60).floor
  7. s = s % 60
  8. h = (m / 60).floor
  9. m = m % 60
  10. d = (h / 24).floor
  11. h = h % 24
  12.  
  13. output = "#{s} second#{Utils.pluralize(s)}" if (s > 0)
  14. output = "#{m} minute#{Utils.pluralize(m)}, #{s} second#{Utils.pluralize(s)}" if (m > 0)
  15. output = "#{h} hour#{Utils.pluralize(h)}, #{m} minute#{Utils.pluralize(m)}, #{s} second#{Utils.pluralize(s)}" if (h > 0)
  16. output = "#{d} day#{Utils.pluralize(d)}, #{h} hour#{Utils.pluralize(h)}, #{m} minute#{Utils.pluralize(m)}, #{s} second#{Utils.pluralize(s)}" if (d > 0)
  17.  
  18. return output
  19. end
  20.  
  21. def self.pluralize number
  22. return "s" unless number == 1
  23. return ""
  24. end
  25.  
  26. end

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.