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

前端 未结 9 459
不知归路
不知归路 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:26

    Rails has an helper which converts distance of time in words. You can look its implementation: distance_of_time_in_words

    0 讨论(0)
  • 2020-12-02 06:31

    You can use 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.

    2.2.2 :062 > formatted_duration 3661
     => "1 h 1 m 1 s"
    
    0 讨论(0)
  • 2020-12-02 06:39

    I just start writing ruby. i guess this is only for 1.9.3

    def dateBeautify(t)
    
        cute_date=Array.new
        tables=[ ["day", 24*60*60], ["hour", 60*60], ["minute", 60], ["sec", 1] ]
    
        tables.each do |unit, value|
            o = t.divmod(value)
            p_unit = o[0] > 1 ? unit.pluralize : unit
            cute_date.push("#{o[0]} #{unit}") unless o[0] == 0
            t = o[1]
        end
        return cute_date.join(', ')
    
    end
    
    0 讨论(0)
提交回复
热议问题