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

后端 未结 13 783
一整个雨季
一整个雨季 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:25

    Using Time.utc.strftime works only for values when total number of hours is less then 24:

    2.2.2 :004 > Time.at(60 * 60).utc.strftime('%H h %M m')
    => "01 h 00 m"
    

    For greater values it returns incorrect results:

    2.2.2 :006 > Time.at(60 * 60 * 24).utc.strftime('%H h %M m')
     => "00 h 00 m"
    

    I suggest using the simplest method I found for this problem:

      def formatted_duration total_seconds
        hours = total_seconds / (60 * 60)
        minutes = (total_seconds / 60) % 60
        seconds = total_seconds % 60
        "#{ hours } h #{ minutes } m #{ seconds } s"
      end
    

    You can always adjust returned value to your needs.

提交回复
热议问题