how to convert 270921sec into days + hours + minut

2019-01-10 04:33发布

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?

标签: ruby time
8条回答
Root(大扎)
2楼-- · 2019-01-10 04:59

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

查看更多
趁早两清
3楼-- · 2019-01-10 05:13

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
查看更多
走好不送
4楼-- · 2019-01-10 05:16

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
查看更多
Ridiculous、
5楼-- · 2019-01-10 05:18

It can be done pretty concisely using divmod:

t = 270921
mm, ss = t.divmod(60)            #=> [4515, 21]
hh, mm = mm.divmod(60)           #=> [75, 15]
dd, hh = hh.divmod(24)           #=> [3, 3]
puts "%d days, %d hours, %d minutes and %d seconds" % [dd, hh, mm, ss]
#=> 3 days, 3 hours, 15 minutes and 21 seconds

You could probably DRY it further by getting creative with collect, or maybe inject, but when the core logic is three lines it may be overkill.

查看更多
贪生不怕死
6楼-- · 2019-01-10 05:20

Needed a break. Golfed this up:

s = 270921
dhms = [60,60,24].reduce([s]) { |m,o| m.unshift(m.shift.divmod(o)).flatten }
# => [3, 3, 15, 21]
查看更多
乱世女痞
7楼-- · 2019-01-10 05:21

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"
查看更多
登录 后发表回答