Aje*_*nga 2 java datetime jodatime
当我试图比较两个DateTime时,我编写了这段代码
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));
Run Code Online (Sandbox Code Playgroud)
预计这将打印
false
false
Run Code Online (Sandbox Code Playgroud)
但事实确实如此
true
false
Run Code Online (Sandbox Code Playgroud)
因此,当我查看持续时间CTOR时,结果发现它实际上创建了一个持续时间为负毫秒的持续时间(getMils()返回-ve).
-ve Duration是什么意思?(保持非常客观)这是一个错误还是一个功能?
听起来对我来说完全合理.你将一个负数毫秒传递给构造函数 - 为什么你会期望它变为正数?
例如,负持续时间只是负时间 - 从"现在"到"过去的某个时间"的时间.它允许合理的算术:
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
Run Code Online (Sandbox Code Playgroud)
没有负的持续时间,这是不可能的.
如果你总是想一个非负的持续时间,只需调用Math.abs
-或在您的情况下,不要使用Duration
在所有的d1
:
long d1 = Math.Abs(dt1.getMillis() - dt2.getMillis());
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
1062 次 |
最近记录: |