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

后端 未结 3 2068
感动是毒
感动是毒 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:32

    Convert seconds into HH:MM:SS in Ruby

    t = 323 # seconds
    Time.at(t).utc.strftime("%H:%M:%S")
    => "00:03:56"
    
    0 讨论(0)
  • 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"
    
    0 讨论(0)
  • 2021-02-15 18:44

    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.

    0 讨论(0)
提交回复
热议问题