Joda Time - 结果不一致
我对 Joda-Time 库中的 daysBetween 函数进行了快速测试,但得到的结果不一致。其他人也有同样的问题吗?
下面是我用于测试的代码。
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());
}
}
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());
}
}
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。

绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(1)
首先,也是主要问题:您在
new Date()
和Calendar.getInstance()
中两次向 Java 询问“当前日期时间”,并且您无法确定这两个调用将在同一时刻返回,或者它们可能在几毫秒内返回。此外,由于您使用的是
DateTime
而不是LocalDate
,几毫秒的差异可能会改变经过天数的计算。如果您(概念上)处理日期之间的差异并且不关心时间(h:m:s.sss),也许您应该更好地使用LocalDate
。第一个问题可以通过仅询问一次 Java 当前日期来解决:
此外(或者,这也可以修复不一致的结果),您可以使用
LocalDate
而不是DateTime
。First, and main problem: you are asking Java for the "current datetime" twice, in
new Date()
and inCalendar.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 ofLocalDate
, 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 useLocalDate
.The first problem could be solved by asking for Java current datime only once:
In addition (or alternatively; this also fixes the inconsistent results), you could use
LocalDate
instead ofDateTime
.