Delphi 2010 中 TTimeSpan 用法的混乱
我尝试了Delphi 2010中新的记录类型TTimeSpan。但是我遇到了一个非常奇怪的问题。
assert(TTimeSpan.FromMilliseconds(5000).Milliseconds = 5000);
这个说法不成立。 'TTimeSpan.FromMilliseconds(5000).Milliseconds' 的值预计为 5000,但实际为 0。
我更深入地挖掘:
function TTimeSpan.GetMilliseconds: Integer;
begin
Result := Integer((FTicks div TicksPerMillisecond) mod 1000);
end;
FTicks = 50000000
TicksPerMillisecond = 10000
FTick div TicksPerMillisecond = 50000000 div 10000 = 5000
(FTick div TicksPerMillisecond) mod 1000 = 5000 mod 1000 = 0 // I do not understand, why mod 1000
Integer((FTick div TicksPerMillisecond) mod 1000) = Integer(0) = 0
我的代码解释是正确的,不是吗?
更新:方法 GetTotalMilliseconds(双精度)已正确实现。
I tried the new Record type TTimeSpan in Delphi 2010. But I encountered a very strange problem.
assert(TTimeSpan.FromMilliseconds(5000).Milliseconds = 5000);
This assertion does not pass. The value of 'TTimeSpan.FromMilliseconds(5000).Milliseconds' is expected to be 5000, but it was 0.
I dig deeper:
function TTimeSpan.GetMilliseconds: Integer;
begin
Result := Integer((FTicks div TicksPerMillisecond) mod 1000);
end;
FTicks = 50000000
TicksPerMillisecond = 10000
FTick div TicksPerMillisecond = 50000000 div 10000 = 5000
(FTick div TicksPerMillisecond) mod 1000 = 5000 mod 1000 = 0 // I do not understand, why mod 1000
Integer((FTick div TicksPerMillisecond) mod 1000) = Integer(0) = 0
My code interpretation is correct, isn't it?
UPDATE: The method GetTotalMilliseconds (double precision) is implemented correctly.
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(2)
您混淆了给出以给定单位表示的总金额的属性与给出将值分解为各个组成部分时的值部分(天、小时、分钟、秒、毫秒、滴答声)。
通过这些,您可以获得每个类别的整数余数。因此,
毫秒
将始终介于 0 和 999(每秒毫秒数 - 1)之间。或者,再举一个例子,如果您有 72 分钟,则
TotalMinutes
为 72,但Minutes
为 12。它与分解
TDateTime
的DecodeDateTime
函数非常相似。对于您想要实现的目标,您肯定需要使用
TotalMilliseconds
属性,正如 TridenT 指出的那样,但是GetMilliseconds
的代码在TimeSpan< 中确实是正确的/代码>。
You are confusing the properties giving the total amount expressed in a given unit with the properties giving the portion of a value when you break it up into its components (days, hours, minutes, seconds, milliseconds, ticks).
With those, you get the integer remainder for each category. So,
Milliseconds
will always be between 0 and 999 (Number Of Milliseconds Per Second - 1).Or, another example, if you have 72 minutes,
TotalMinutes
is 72, butMinutes
is 12.It is very much similar to the
DecodeDateTime
function to break up aTDateTime
.And for what you want to achieve, you definitely need to use the
TotalMilliseconds
property, as TridenT pointed out, but the code forGetMilliseconds
is indeed correct inTimeSpan
.您必须使用
TotalMilliseconds
而不是Milliseconds
属性。效果更好!
来自文档:
You must use
TotalMilliseconds
instead ofMilliseconds
property.It works better !
From documentation: