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

后端 未结 3 2067
感动是毒
感动是毒 2021-02-15 17:49

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 c

3条回答
  •  情话喂你
    2021-02-15 18:34

    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"
    

提交回复
热议问题