dateutils: function DateTimeToUnix miscalculates
Original Reporter info from Mantis: warrence
-
Reporter name: Stefan Müller
Original Reporter info from Mantis: warrence
- Reporter name: Stefan Müller
Description:
Hi.
The result provided by DateTimeToUnix is wrong in most cases.
Line 2043 in rtl/objpas/dateutil.inc:
Function DateTimeToUnix(const AValue: TDateTime): Int64;
begin
Result:=SecondsBetween(UnixEpoch, AValue);
end;
Because SecondsBetween always returns positive values, it is impossible to translate dates before 1970. If one tries so he'll get a date after 1970 with the same distance to 1970.
Line 1322 in rtl/objpas/dateutil.inc
Function SecondsBetween(const ANow, AThen: TDateTime): Int64;
begin
Result:=Trunc(Abs(ANow-AThen)*SecsPerDay);
end;
Furthermore, the usage of Trunc is not suitable in this case (see additional information).
Thanks.
Additional information:
By using Trunc the Result of DateTimeToUnix is wrong in about 99.9% of the cases. A big portion of the range of Integer (32 bit) was tested for invertibility: i = DateTimeToUnix(UnixToDateTime(i)) ?
Both errors can be fixed by replacing the current implementation of DateTimeToUnix by the following:
Function DateTimeToUnix(const AValue: TDateTime): Int64;
begin
Result:=Round((AValue-UnixEpoch)*SecsPerDay);
end;
(SecondsBetween is nevertheless correct implemented, as far as I notice.)
Mantis conversion info:
- Mantis ID: 12936
- Version: 2.2.3
- Fixed in version: 2.4.0
- Fixed in revision: 12958 (#6a813b8e)
- Monitored by: » Joost (Joost van der Sluis)