'negative' Duration in Joda, a bug or a feature?

When trying to compare two DateTime I wrote this code

private boolean compareTime(DateTime dt1, DateTime dt2) 
{ 
    long d1 = (new Duration(dt1.getMillis() - dt2.getMillis())).getMillis();
    long d2 = Duration.standardHours(1).getMillis(); 
    return  d1  < d2; 
}
DateTime dt1 = new DateTime();
Thread.sleep(250);
DateTime dt2 = dt1.plusHours(2);
System.out.println(compareTime(dt1,dt2));
System.out.println(compareTime(dt2,dt1));

Expected this to print

false
false

But it was

true
false

So when I looked into Duration CTOR, then turned out it actually created a Duration with negative millisecond duration (getMils() returns -ve).

What is the meaning of -ve Duration ? (To keep it very objective) Is this a bug or a feature ?

Jon Skeet
people
quotationmark

Sounds entirely sensible to me. You're passing a negative number of milliseconds into the constructor - why would you expect that to become positive?

A negative duration is simply a negative amount of time - the time from "now" to "some time in the past", for example. It allows sensible arithmetic:

Instant x = ...;
Instant y = ...;
// Duration from x to y, although the result isn't "anchored" (it forgets x and y)
Duration d = new Duration(x, y);
Instant y2 = x.plus(d); // y2 is now equal to y

Without negative durations, this would be impossible.

If you always want a non-negative duration, just call Math.abs - or in your case, don't use Duration at all for d1:

long d1 = Math.Abs(dt1.getMillis() - dt2.getMillis());

people

See more on this question at Stackoverflow