问题
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());
}
}
回答1:
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.
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
.
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();
}
In addition (or alternatively; this also fixes the inconsistent results), you could use LocalDate
instead of DateTime
.
来源:https://stackoverflow.com/questions/8711244/joda-time-inconsistent-result