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 :)
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"
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.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With