Cameron Cameron - 25 days ago 15
Ruby Question

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.

Answer

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
Comments