how to convert 270921sec into days + hours + minutes + sec ? (ruby)

前端 未结 9 629
不知归路
不知归路 2020-12-02 06:09

I have a number of seconds. Let\'s say 270921. How can I display that number saying it is xx days, yy hours, zz minutes, ww seconds?

9条回答
  •  情书的邮戳
    2020-12-02 06:15

    I modified the answer given by @Mike to add dynamic formatting based on the size of the result

          def formatted_duration(total_seconds)
            dhms = [60, 60, 24].reduce([total_seconds]) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
    
            return "%d days %d hours %d minutes %d seconds" % dhms unless dhms[0].zero?
            return "%d hours %d minutes %d seconds" % dhms[1..3] unless dhms[1].zero?
            return "%d minutes %d seconds" % dhms[2..3] unless dhms[2].zero?
            "%d seconds" % dhms[3]
          end
    

提交回复
热议问题