乔达时间-不一致的结果 [英] Joda Time - inconsistent result
问题描述
我对Joda-Time库中的daysBetween
函数进行了快速测试,结果不一致.还有其他人有同样的问题吗?
I ran a quick test on daysBetween
function in Joda-Time library and I am getting inconsistent result. Does anyone else have the same problem?
下面是我用于测试的代码.
Below is the code I use for testing.
public static int elapsedDaysJoda() {
DateTime dt1 = new DateTime(new Date());
Calendar cal = Calendar.getInstance();
cal.set(2011, 0, 1);
DateTime dt2 = new DateTime(cal.getTime());
Days days = Days.daysBetween(dt2, dt1);
return days.getDays();
}
public static void main(String[] args) {
for(int i=0; i < 10; i++) {
System.out.println(elapsedDaysJoda());
}
}
推荐答案
首先,也是主要问题:您正在Java中两次在new Date()
和Calendar.getInstance()
中向Java请求当前日期时间",因此不能确定这两个调用将返回完全相同的时刻,或者如果它们可以在几毫秒内有所不同,则返回.
First, and main problem: you are asking Java for the "current datetime" twice, in new Date()
and in Calendar.getInstance()
, and you cannot be sure that this two calls will return exactly the same instant or if they can differ in a few milliseconds.
此外,因为您使用的是DateTime
而不是LocalDate
,所以几毫秒的差异可能会改变经过时间的计算.如果您(从概念上)正在处理几天之间的差异,并且您不关心时间(h:m:s.ssss),那么您最好使用LocalDate
.
Besides, because you are using DateTime
instead of LocalDate
, that difference of a few milliseconds can alter the calculation of the elapsed days. If you are (conceptually) dealing with difference between days and you do not care about times (h:m:s.sss) perhaps you should better use LocalDate
.
第一个问题可以通过只请求Java当前时间来解决:
The first problem could be solved by asking for Java current datime only once:
public static int elapsedDaysJoda() {
Calendar cal = Calendar.getInstance();
DateTime dt1 = new DateTime(cal);
cal.set(2011, 0, 1);
DateTime dt2 = new DateTime(cal.getTime());
Days days = Days.daysBetween(dt2, dt1);
return days.getDays();
}
此外(或替代;这也可以修复不一致的结果),您可以使用LocalDate
代替DateTime
.
In addition (or alternatively; this also fixes the inconsistent results), you could use LocalDate
instead of DateTime
.
这篇关于乔达时间-不一致的结果的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!