user6447029
user6447029

Reputation:

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?

Upvotes: 2

Views: 269

Answers (2)

Alexandre Angelim
Alexandre Angelim

Reputation: 6773

Just another implementation.. Cause it's fun :)

def duration_in_milliseconds(string)
  string.split(':')
  .map(&:to_i)
  .reverse
  .zip([1,60,3600])
  .map{ |segment, multiplier| segment*multiplier }
  .inject(:+) * 1000
end

Upvotes: 0

Andrey Deineko
Andrey Deineko

Reputation: 52367

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

Upvotes: 1

Related Questions