Cameron
Cameron

Reputation: 28783

Convert milliseconds to hours and mins in ruby

I have the following Rails helper to convert milliseconds to hours and mins:

def get_duration_hrs_and_mins(duration)
  hours = duration / (3600000 * 3600000)
  minutes = (duration / 60000) % 60000
  "#{hours}h #{minutes}m" 
rescue
  ""
end

However it always just returns it in minutes (e.g. 364m) and doesn't show the hours... and keep the minutes under 60.

Upvotes: 0

Views: 7384

Answers (2)

Stefan
Stefan

Reputation: 114138

Your calculations are off:

  • a second has 1000 milliseconds
  • a minute has 1000 × 60 milliseconds
  • an hour has 1000 × 60 × 60 milliseconds

To get the number of (full) hours, you have to divide the number of milliseconds by 1000 × 60 × 60. The remainder can then be used to calculate the number of minutes in a similar way.

This is what divmod is for:

def get_duration_hrs_and_mins(milliseconds)
  return '' unless milliseconds

  hours, milliseconds   = milliseconds.divmod(1000 * 60 * 60)
  minutes, milliseconds = milliseconds.divmod(1000 * 60)
  seconds, milliseconds = milliseconds.divmod(1000)
  "#{hours}h #{minutes}m #{seconds}s #{milliseconds}ms"
end

get_duration_hrs_and_mins(123456789)
#=> "34h 17m 36s 789ms"

I've added seconds and milliseconds to the output for demonstration purposes. And I've also replaced the rescue block with a guard clause, assuming that you want to handle nil values.

Upvotes: 6

David
David

Reputation: 3610

You have miscalculated the number of milliseconds in 1 hour and 1 minute. Try the following:

def get_duration_hrs_and_mins(duration)
  hours = duration / (1000 * 60 * 60)
  minutes = duration / (1000 * 60) % 60
  "#{hours}h #{minutes}m" 
rescue
  ""
end

Upvotes: 6

Related Questions