将 Ruby 中的持续时间 - hh:mm:ss.sss 转换为毫秒,反之亦然 [英] Convert durations in Ruby - hh:mm:ss.sss to milliseconds and vice versa

查看:52
本文介绍了将 Ruby 中的持续时间 - hh:mm:ss.sss 转换为毫秒,反之亦然的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我想知道 Ruby 中是否有一个内置方法可以让我将 hh:mm:ss.sss 格式的单圈时间转换为毫秒,反之亦然.由于我需要用它做一些计算,我认为转换为毫秒是最简单的方法.如果我错了,请告诉我:)

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

推荐答案

这个怎么样?

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"

这篇关于将 Ruby 中的持续时间 - hh:mm:ss.sss 转换为毫秒,反之亦然的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆