为什么TTime比较会产生意想不到的结果? [英] Why do TTime comparisons give unexpected results?
问题描述
我已经观察到关于 EncodeDateTime
和 EncodeTime
方法的一些奇怪行为,我正在寻求一些解释。
I have observed some kind of weird behaviour regarding the EncodeDateTime
and EncodeTime
methods and I am seeking some explanation.
procedure SomeTestCase;
var
time: TTime;
dateTime: TDateTime;
begin
time := EncodeTime(8, 0, 0, 0);
date := EncodeDateTime(2012, 11, 2, 8, 0, 0, 0);
Assert(time = TimeOf(date)); //Fails
end;
我发现是 date
小时部分评估为 7:59:59
,而不是 8:00:00
。但是如果将时间
和 date
的小时部分设置为9,则断言通过,日期
评估为预期值。有些小时工作,而其他人则没有。有人可以解释我发生了什么吗?
What I've found is that date
's hour portion evaluates to 7:59:59
instead of 8:00:00
. But if I set the hour portion of time
and date
to 9, the assert passes and date
evaluates to the expected value. Some hours work while some others don't. Can somebody explain me what is going on?
推荐答案
时间值( TTime
, TDate
, TDateTime
)实际上是一个 double
(即浮点值),其中日期编码在整数部分中,而时间由小数部分编码。测试浮点值的平等总是有风险的。
A time value (TTime
, TDate
, TDateTime
) is actually a double
(that is, a floating-point value), with the date encoded in the integer part, and the time encoded in by fractional part. And it is always risky to test equality of floating-point values.
您可以使用 SameTime(时间,日期)
而不是结果:= Abs(Frac(A) - Frac(B))< OneMillisecond;
You can use SameTime(time, date)
instead. This compensates correctly for 'numerical fuss': Result := Abs(Frac(A) - Frac(B)) < OneMillisecond;
这篇关于为什么TTime比较会产生意想不到的结果?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!