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

Viewed 40702

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?

10 Answers

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.

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

Number of days = 270921/86400 (Number of seconds in day) = 3 days this is the absolute number

seconds remaining (t) = 270921 - 3*86400 = 11721

3.to_s + Time.at(t).utc.strftime(":%H:%M:%S")

Which will produce something like 3:03:15:21

Not a direct answer to the OP but it might help someone who lands here.

I had this string

"Sorry, you cannot change team leader in the last #{freeze_period_time} of a #{competition.kind}"

freeze_period_time resolved to 5 days inside irb, but inside the string, it resolved to time in seconds eg 47200, so the string became something ugly

"Sorry, you cannot change team leader in the last 47200 of a hackathon"

To fix it, I had to use .inspect on the freeze_period_time object.

So the following made it work

"Sorry, you cannot change team leader in the last #{freeze_period_time.inspect} of a #{competition.kind}"

Which returned the correct sentence

"Sorry, you cannot change team leader in the last 5 days of a hackathon"

TLDR

You might need time.inspect - https://www.geeksforgeeks.org/ruby-time-inspect-function/

Related