Joda的“负”持续时间,错误或功能? [英] 'negative' Duration in Joda, a bug or a feature?
问题描述
尝试比较两个DateTime时,我写了这段代码
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));
期望此打印
false
false
但这是
true
false
因此,当我查看持续时间CTOR时,发现它实际上创建了一个带有负毫秒持续时间的持续时间(getMils()返回-ve)。
So when I looked into Duration CTOR, then turned out it actually created a Duration with negative millisecond duration (getMils() returns -ve).
什么是-ve持续时间的含义是什么?
(为了保持客观性)
这是Bug还是功能?
What is the meaning of -ve Duration ? (To keep it very objective) Is this a bug or a feature ?
推荐答案
听起来对我完全明智。您将负数毫秒传递给构造函数-为什么您要期望变为正数?
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.
如果您始终希望持续时间为非负数,只需致电 Math.abs
-否则,请不要使用持续时间
对于 d1
:
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());
这篇关于Joda的“负”持续时间,错误或功能?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!