Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Why do TTime comparisons give unexpected results?

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;

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?

like image 788
marco-fiset Avatar asked Nov 02 '12 19:11

marco-fiset


1 Answers

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.

You can use SameTime(time, date) instead. This compensates correctly for 'numerical fuss': Result := Abs(Frac(A) - Frac(B)) < OneMillisecond;

like image 160
Andreas Rejbrand Avatar answered Oct 30 '22 09:10

Andreas Rejbrand