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

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

    I use this to show time durations in my Rails Project:

    1. Add a custom method to the Integer class. You can create a new file called pretty_duration.rb in the initializers folder:

      class Integer
          def pretty_duration
              parse_string = 
                  if self < 3600
                      '%M:%S'
                  else
                      '%H:%M:%S'
                  end
      
              Time.at(self).utc.strftime(parse_string)
          end
      end
      
    2. Call seconds.pretty_duration anywhere in your project:

      275.pretty_duration     # => "04:35"
      9823.pretty_duration    # => "02:43:43"
      

    This answer builds up on Lev Lukomsky's Code

提交回复
热议问题