Mike Mike - 2 months ago 11
Ruby Question

How do I convert this string to milliseconds?

I’m using Rails 4.2.7. I want to calculate the number of milliseconds given a duration, which could include hours, minutes, and seconds. So I wrote these two functions:

def convert_to_hrs(string)
if !string.nil?
string.strip!
case string.count(':')
when 0
'00:00:' + string.rjust(2, '0')
when 1
'00:' + string
else
string
end
else
"00:00:00"
end
end

def duration_in_milliseconds(input)
input = convert_to_hrs(input)
if input.match(/\d+:\d\d:\d\d\.?\d*/)
h, m, s = input.split(':').map(&:to_i)
(h.hours + m.minutes + s.seconds) * 1000
else
0
end
end


Unfortunately, when I call
duration_in_milliseconds(input)
with a number like
8:49
, the result is
zero
. The result should be interpreted as
8 minutes and 49 seconds
, which in milliseconds would be
529000
. How do I adjust the above to account for this?

Answer

I'll just leave this one here:

def convert_to_ms(string)
  string.split(':').map(&:to_i).inject(0) { |a, b| a * 60 + b } * 1000
end

convert_to_ms('8:49')
#=> 529000
Comments