IDE: API
Version: newest
Target (If relevant): Java (Cooper), JDK 1.8, Elements RTL (com.remobjects.elements.rtl.jar)
Description:
On Cooper, DateTime.CompareTo returns a non-zero value when a DateTime is compared with itself, if the underlying java.util.Calendar is in any time zone other than UTC. It also disagrees with the DateTime operators: d = d is True while d.CompareTo(d) is -1. Values that differ only in milliseconds compare as equal.
Cause, in Source/RemObjects.Elements.RTL/DateTime.pas (Cooper branch of CompareTo):
result := mapped.compareTo(new DateTime(aValue.Year, aValue.Month, aValue.Day,
aValue.Hour, aValue.Minute, aValue.Second));
aValue.Year … aValue.Secondread wall-clock fields in the time zone ofaValue’s calendar (mapped.get(Calendar.XXX)).new DateTime(y, m, d, h, n, s)builds a calendar inTimeZone.Utcfrom them, so the argument is shifted by the zone offset ofaValue.- Milliseconds are dropped.
- The operators
=,<,>,<=,>=compareTicks(TimeInMillis + TimeZone.getOffset(TimeInMillis)) and are correct.
Impact:
CompareToandDateTime.Comparegive different results on Java than on .NET and Island.- A sort comparator based on
CompareToreportsx < x. Java’s TimSort may then throwIllegalArgumentException: Comparison method violates its general contract! - The result depends on the machine’s time zone, so the bug does not show on machines that run in UTC.
Suggested fix: compare Ticks, so that CompareTo and the operators always agree:
{$IF COOPER}
var t1 := Ticks;
var t2 := aValue.Ticks;
result := if t1 < t2 then -1 else if t1 > t2 then 1 else 0;
{$ENDIF}
Expected Behavior:
d.CompareTo(d) returns 0. In general, CompareTo agrees with the = / < / > operators, including milliseconds, regardless of the calendar’s time zone:
d.CompareTo(d) = 0
d = d = True
a.CompareTo(b) = -1
a < b = True
Actual Behavior:
d.CompareTo(d) = -1
d = d = True
a.CompareTo(b) = 0
a < b = True
Steps:
- Use a machine (or JVM default time zone) other than UTC; we use
Europe/Belgrade. - Build and run this Cooper console application:
namespace DateTimeCompareTest;
uses
RemObjects.Elements.RTL;
type
Program = class
public
class method Main(args: array of String): Int32;
begin
// any default zone other than UTC
java.util.TimeZone.Default := java.util.TimeZone.getTimeZone('Europe/Belgrade');
var d := new DateTime(2020, 1, 15);
java.util.Calendar(d).setTimeZone(java.util.TimeZone.Default);
writeLn('d.CompareTo(d) = ' + d.CompareTo(d));
writeLn('d = d = ' + (d = d));
var a := new DateTime(2020, 1, 15, 10, 0, 0, 0);
var b := new DateTime(2020, 1, 15, 10, 0, 0, 500);
writeLn('a.CompareTo(b) = ' + a.CompareTo(b));
writeLn('a < b = ' + (a < b));
end;
end;
end.
- Compare the output with the expected values above.
We are adding a workaround on our side that compares Ticks instead of calling CompareTo on Cooper. We would prefer to remove the workaround once the RTL is fixed.