Last active
August 18, 2024 01:10
-
-
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.
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
# 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
Hii