DaysBetween issue when zero date is crossed
Summary
Calculating the day difference between dates on both sides of the TDateTime origin (Dec 30 1899) I noticed that the result can be off by 1.
System Information
- Operating system: tested on Win 11
- Processor architecture: x86
- Compiler version: trunc (git hash: 76aa9b1f)
- Device: Computer
Steps to reproduce
program Project1;
uses
SysUtils, DateUtils;
var
dt1, dt2: TDateTime;
begin
dt1 := 1.0;
dt2 := IncDay(dt1, -2); // two days earlier
WriteLn(dt1:0:6, ' ', DateTimeToStr(dt1));
WriteLn(dt2:0:6, ' ', DateTimeToStr(dt2));
WriteLn(DaysBetween(dt1, dt2));
WriteLn(DaysBetween(dt2, dt1));
ReadLn;
end.
dt2 is constructed to be two days earlier than dt1. But DaysBetween reports a difference of only 1 day. This is also in contradiction with Delphi which reports the correct value of 2.
However, when the time part of dt1 is slightly later than 6:00 (d1 = 1.25 + OneMillisecond) the result is correct. This might be related to the mystic handling of the 0.5 in the source code (in datetimeutil.inc):
Function DateTimeDiff(const ANow, AThen: TDateTime): TDateTime;
begin
Result:= ANow - AThen;
if (ANow>0) and (AThen<0) then
Result:=Result-0.5
else if (ANow<-1.0) and (AThen>-1.0) then
Result:=Result+0.5;
end;