tags:

views:

482

answers:

2

Hey there,

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 :)

Cheers, Chris

+2  A: 

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.

Mladen Jablanović
If I add the milliseconds, this should work. Will try that out later. Thanks :)
herrherr
It already works with the milliseconds, you just pass seconds as Float or Rational (`time_to_day_fraction(1,45,22.345)`).
Mladen Jablanović
Doesn't work with a float, I get "a undefined method `gcd'".
herrherr
You're right, sorry, I tried only in ruby 1.9.1 and assumed it would work in previous versions as well. Well, you could either use Rational, add milliseconds parameter to the methods, or use Jonas' methods. ;)
Mladen Jablanović
+1  A: 

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"
Jonas Elfström
Took me quite some time to understand it fully, but works like a charm :) Thanks for that.
herrherr
Sorry, I ought to put some comments in there instead of code golfing.
Jonas Elfström