Convert duration to hours:minutes:seconds (or similar) in Rails 3 or Ruby

后端 未结 13 758
一整个雨季
一整个雨季 2021-01-29 23:52

I have a feeling there is a simple/built-in way to do this but I can\'t find it.

I have a duration (in seconds) in an integer and I want to display it in a friendly form

13条回答
  •  北恋
    北恋 (楼主)
    2021-01-30 00:24

    This one uses the obscure divmod method to divide and modulo at the same time, so it handles Float seconds properly:

    def duration(seconds)
      minutes, seconds = seconds.divmod(60)
      hours, minutes = minutes.divmod(60)
      days, hours = hours.divmod(24)
    
      "#{days.to_s.rjust(3)}d #{hours.to_s.rjust(2)}h #{minutes.to_s.rjust(2)}m #{seconds}s"
    end
    

提交回复
热议问题