在 Ruby 中计算持续时间与毫秒之间的差异
TL;DR: 我需要了解
HH:MM:SS.ms
和HH:MM:SS.ms
之间的区别为HH:MM:SS:ms
我需要什么:
这是一个棘手的问题。我正在尝试计算两个时间戳之间的差异,如下所示:
In: 00:00:10.520
Out: 00:00:23.720
应交付:
Diff: 00:00:13.200
我认为我会将时间解析为实际的 Time 对象并使用其中的差异。这在前一种情况下效果很好,并返回 00:0:13.200
。
什么不起作用:
但是,对于某些人来说,这不起作用,因为 Ruby 使用 usec
而不是 msec
:
In: 00:2:22.760
Out: 00:2:31.520
Diff: 00:0:8.999760
显然,区别应该是 00 :00:8:760
而不是 00:00:8.999760
。 我真的很想 tdiff.usec.to_s.gsub('999','')
……
到目前为止我的代码:
这是到目前为止我的代码(这些从输入字符串(如“0:00:10:520”)中解析。
tin_first, tin_second = ins.split(".")
tin_hours, tin_minutes, tin_seconds = tin_first.split(":")
tin_usec = tin_second * 1000
tin = Time.gm(0, 1, 1, tin_hours, tin_minutes, tin_seconds, tin_usec)
tout
也会发生同样的情况。然后:
tdiff = Time.at(tout-tin)
对于输出,我使用:
"00:#{tdiff.min}:#{tdiff.sec}.#{tdiff.usec}"
有没有更快的方法来做到这一点?请记住,我只想得到两个时间之间的差异。我缺少什么?
我现在使用的是 Ruby 1.9.3p6。
TL;DR: I need to get the difference between
HH:MM:SS.ms
andHH:MM:SS.ms
asHH:MM:SS:ms
What I need:
Here's a tricky one. I'm trying to calculate the difference between two timestamps such as the following:
In: 00:00:10.520
Out: 00:00:23.720
Should deliver:
Diff: 00:00:13.200
I thought I'd parse the times into actual Time
objects and use the difference there. This works great in the previous case, and returns 00:0:13.200
.
What doesn't work:
However, for some, this doesn't work right, as Ruby uses usec
instead of msec
:
In: 00:2:22.760
Out: 00:2:31.520
Diff: 00:0:8.999760
Obviously, the difference should be 00:00:8:760
and not 00:00:8.999760
. I'm really tempted to just tdiff.usec.to_s.gsub('999','')
……
My code so far:
Here's my code so far (these are parsed from the input strings like "0:00:10:520").
tin_first, tin_second = ins.split(".")
tin_hours, tin_minutes, tin_seconds = tin_first.split(":")
tin_usec = tin_second * 1000
tin = Time.gm(0, 1, 1, tin_hours, tin_minutes, tin_seconds, tin_usec)
The same happens for tout
. Then:
tdiff = Time.at(tout-tin)
For the output, I use:
"00:#{tdiff.min}:#{tdiff.sec}.#{tdiff.usec}"
Is there any faster way to do this? Remember, I just want to have the difference between two times. What am I missing?
I'm using Ruby 1.9.3p6 at the moment.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(3)
使用
Time
:这是一个不依赖于
Time
的解决方案:Using
Time
:Here's a solution that doesn't rely on
Time
:我认为以下内容可行:
它确实打印一小时的
01
,但我不太明白。与此同时,我使用了:
当然,任何做得更好的答案都会得到赞成票或接受。
I figured the following could work:
It does print
01
for the hour, which I don't really understand.In the meantime, I used:
Any answer that does this better will get an upvote or the accept, of course.
输出:
Time.parse(out_time) - Time.parse(in_time)
给出以秒
为单位的结果,乘以1000
以转换为毫秒
。OUTPUT:
Time.parse(out_time) - Time.parse(in_time)
gives the result inseconds
so multiplied by1000
to convert intomilliseconds
.