Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Convert durations in Ruby - hh:mm:ss.sss to milliseconds and vice versa

Tags:

time

ruby

I was wondering if there is a built-in method in Ruby that allows me to convert lap times in the format of hh:mm:ss.sss to milliseconds and vice versa. Since I need to do some calculations with it, I assumed that converting to milliseconds would be the easiest way to do this. Tell me if I am wrong here :)

like image 408
herrherr Avatar asked Mar 04 '10 09:03

herrherr


2 Answers

How about this?

a=[1, 1000, 60000, 3600000]*2
ms="01:45:36.180".split(/[:\.]/).map{|time| time.to_i*a.pop}.inject(&:+)
# => 6336180
t = "%02d" % (ms / a[3]).to_s << ":" << 
    "%02d" % (ms % a[3] / a[2]).to_s << ":" << 
    "%02d" % (ms % a[2] / a[1]).to_s << "." << 
    "%03d" % (ms % a[1]).to_s
# => "01:45:36.180"
like image 186
Jonas Elfström Avatar answered Sep 29 '22 08:09

Jonas Elfström


As you are ignoring the date altogether, and possibly have numbers greater than 24 as number of hours, maybe existing Ruby classes aren't suitable for you (at least ones from the standard lib).

Actually, there are couple of methods which might be helpful: time_to_day_fraction and day_fraction_to_time, but for some reason they are private (at least in 1.9.1).

So you can either monkey-patch them to make them public, or simply copy-paste their implementation to your code:

def time_to_day_fraction(h, min, s)
  Rational(h * 3600 + min * 60 + s, 86400) # 4p
end

def day_fraction_to_time(fr)
  ss,  fr = fr.divmod(Rational(1, 86400)) # 4p
  h,   ss = ss.divmod(3600)
  min, s  = ss.divmod(60)
  return h, min, s, fr
end

They are working with Rational class, so you can calculate easily with them.

like image 35
Mladen Jablanović Avatar answered Sep 29 '22 09:09

Mladen Jablanović