Joda Time - 结果不一致

发布于 2024-12-23 19:51:36 字数 567 浏览 0 评论 0原文

我对 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 技术交流群。

扫码二维码加入Web技术交流群

发布评论

需要 登录 才能够评论, 你可以免费 注册 一个本站的账号。

评论(1

渡你暖光 2024-12-30 19:51:36

首先,也是主要问题:您在 new Date()Calendar.getInstance() 中两次向 Java 询问“当前日期时间”,并且您无法确定这两个调用将在同一时刻返回,或者它们可能在几毫秒内返回。

此外,由于您使用的是 DateTime 而不是 LocalDate,几毫秒的差异可能会改变经过天数的计算。如果您(概念上)处理日期之间的差异并且不关心时间(h:m:s.sss),也许您应该更好地使用 LocalDate

第一个问题可以通过仅询问一次 Java 当前日期来解决:

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

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.

~没有更多了~
我们使用 Cookies 和其他技术来定制您的体验包括您的登录状态等。通过阅读我们的 隐私政策 了解更多相关信息。 单击 接受 或继续使用网站,即表示您同意使用 Cookies 和您的相关数据。
原文