最近计算两时间的秒数之差,发现用 SecondsBetween 会出现有误差的现象
2020-11-15 00:00:00 - 2020-11-15 00:00:00 = 0
2020-11-15 00:00:00 - 2020-11-15 00:00:01 = 1
2020-11-15 00:00:00 - 2020-11-15 00:00:02 = 1
2020-11-15 00:00:00 - 2020-11-15 00:00:03 = 3
2020-11-15 00:00:00 - 2020-11-15 00:00:04 = 4
2020-11-15 00:00:00 - 2020-11-15 00:00:05 = 4
2020-11-15 00:00:00 - 2020-11-15 00:00:06 = 6
2020-11-15 00:00:00 - 2020-11-15 00:00:07 = 6
2020-11-15 00:00:00 - 2020-11-15 00:00:08 = 7
2020-11-15 00:00:00 - 2020-11-15 00:00:09 = 9
2020-11-15 00:00:00 - 2020-11-15 00:00:10 = 9
原因就是时间存在double的小数位,相减的结果取整,而不是四舍五入,改为下面这样就好了
class function TDateUtil.SecondsBetween(const t1, t2: TDateTime): Integer;
begin
Result := Round(MilliSecondsBetween(t1, t2)/1000);
end;