Skip to content

Instantly share code, notes, and snippets.

@redbar0n
Last active December 6, 2020 09:15
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save redbar0n/2eb154b8381994b2c55301bd37f57c1f to your computer and use it in GitHub Desktop.
Save redbar0n/2eb154b8381994b2c55301bd37f57c1f to your computer and use it in GitHub Desktop.
Ruby: Convert seconds to HH:MM:SS time notation without will resetting HH to 00 when crossing 24-hour day boundary.
# Will take as input a time in seconds (which is typically a result after subtracting two Time objects),
# and return the result in HH:MM:SS, but instead of resetting HH to 00 when the time exceeds a 24 hour period,
# it will increase it indefinitely. For other variations, see discussion here: https://gist.github.com/shunchu/3175001
def formatted_duration(total_seconds)
total_seconds = total_seconds.round # to avoid fractional seconds to potentially compound and mess up seconds, minutes and hours
hours = total_seconds / (60*60)
minutes = (total_seconds / 60) % 60 # the modulo operator (%) gives the remainder when leftside is divided by rightside
seconds = total_seconds % 60
[hours, minutes, seconds].map do |t|
# Right justify and pad with 0 until length is 2.
# So if the duration of any of the time components is 0, then it will display as 00
t.round.to_s.rjust(2,'0')
end.join(':')
end
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment