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

自作多情 提交于 2020-01-24 15:02:08

问题


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 ?


回答1:


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());


来源:https://stackoverflow.com/questions/34629281/negative-duration-in-joda-a-bug-or-a-feature

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!