将时间与毫秒进行比较
compare times with milliseconds
我有两个日期,一个开始日期和一个结束日期。我想得到一个新的时间对象,这是两者之间的区别。我关心的差异是小时、分钟、秒和毫秒。我需要能够根据包含毫秒差异的结果创建一个新的 Time 对象
>> require 'time'
=> true
>> start_time = Time.parse '1970-01-01T00:00:00.200'
=> 1970-01-01 00:00:00 +0000
>> end_time = Time.parse '1970-01-01T01:01:01.400'
=> 1970-01-01 01:01:01 +0000
>> difference = Time.at(end_time - start_time)
=> 1970-01-01 01:01:01 +0000
我的问题是差异没有毫秒
通过运行
我可以看出时间有毫秒
>> difference.strftime('%H:%M:%S.%L')
=> "01:01:01.199"
但是如何访问时差对象中的毫秒数。
我在进行亚秒级计算时,毫秒数很重要吗?
更新
我不认为我对这个问题的第一次尝试是描述性的,我对此深表歉意。
require 'time'
a = Time.now
sleep(0.5)
b = Time.now
b - a
# => 0.505087
毫秒!
编辑:微秒!
Ruby 的 Time
class 具有纳秒级精度:您可以使用 Time#to_f
获得自 Unix 纪元以来的小数秒数。如果您减去两个 Time
对象,您将得到它们之间的小数秒。因此,要获得两次之间的毫秒数,请尝试:
((time2 - time1) * 1000).to_i
my problem is that difference does not have the milliseconds
有毫秒,Time#to_s
/ Time#inspect
只是不显示。它的输出相当于:strftime "%Y-%m-%d %H:%M:%S %z"
how do I access the milliseconds that are in the Time difference object.
usec
returns the microseconds and nsec
returns 纳秒:
time = Time.at(0.2)
time.usec #=> 200000
time.nsec #=> 200000000
您可以使用几毫秒
time.usec / 1000 #=> 200
我有两个日期,一个开始日期和一个结束日期。我想得到一个新的时间对象,这是两者之间的区别。我关心的差异是小时、分钟、秒和毫秒。我需要能够根据包含毫秒差异的结果创建一个新的 Time 对象
>> require 'time'
=> true
>> start_time = Time.parse '1970-01-01T00:00:00.200'
=> 1970-01-01 00:00:00 +0000
>> end_time = Time.parse '1970-01-01T01:01:01.400'
=> 1970-01-01 01:01:01 +0000
>> difference = Time.at(end_time - start_time)
=> 1970-01-01 01:01:01 +0000
我的问题是差异没有毫秒
通过运行
我可以看出时间有毫秒>> difference.strftime('%H:%M:%S.%L')
=> "01:01:01.199"
但是如何访问时差对象中的毫秒数。
我在进行亚秒级计算时,毫秒数很重要吗?
更新
我不认为我对这个问题的第一次尝试是描述性的,我对此深表歉意。
require 'time'
a = Time.now
sleep(0.5)
b = Time.now
b - a
# => 0.505087
毫秒!
编辑:微秒!
Ruby 的 Time
class 具有纳秒级精度:您可以使用 Time#to_f
获得自 Unix 纪元以来的小数秒数。如果您减去两个 Time
对象,您将得到它们之间的小数秒。因此,要获得两次之间的毫秒数,请尝试:
((time2 - time1) * 1000).to_i
my problem is that difference does not have the milliseconds
有毫秒,Time#to_s
/ Time#inspect
只是不显示。它的输出相当于:strftime "%Y-%m-%d %H:%M:%S %z"
how do I access the milliseconds that are in the Time difference object.
usec
returns the microseconds and nsec
returns 纳秒:
time = Time.at(0.2)
time.usec #=> 200000
time.nsec #=> 200000000
您可以使用几毫秒
time.usec / 1000 #=> 200