在其他解决方案中,当跨越 24 小时日边界时,小时计数器将重置为 00。还要注意Time.at
四舍五入,所以如果输入有任何小数秒,它会给出错误的结果(例如,什么时候t=479.9
会Time.at(t).utc.strftime("%H:%M:%S")
给出00:07:59
而不是 00:08:00 是正确的)。
如果您想要一种将任意秒数(即使是大于 24 小时跨度的高计数)转换为不断增加的 HH:MM:SS 计数器并处理潜在小数秒数的方法,请尝试以下操作:
# 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, even if it exceeds a 24 hour period.
def formatted_duration(total_seconds)
total_seconds = total_seconds.round # to avoid fractional seconds potentially compounding and messing 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. Ex: 121 % 60 = 1
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
修改自@springerigor's 和https://gist.github.com/shunchu/3175001讨论中的建议