为什么daysBetween在这里错了?

时间:2011-12-28 10:03:16

标签: java jodatime

我正在尝试计算两个日期之间的天数:

public static int getDaysBetweenTwoDates(final LocalDateTime oldDate,
        final LocalDateTime newDate) {
    System.out.println("--Calculate days between: " + oldDate.toString()
            + "->" + newDate);
    Days days = Days.daysBetween(new DateMidnight(oldDate.toDateTime()),
            new DateMidnight(newDate.toDateTime()));
    System.out.println("----DIFF: " + days.size());
    return days.size();
}

好吧,我无法理解为什么12月10日到12月28日之间它会回归" 1"结果:

--Calculate days between: 2011-12-10T00:00:00.000->2011-12-28T12:01:07.577
----DIFF: 1

你看到了什么原因吗?

更新:我还试图保持简单,但仍然无效:

Days days = Days.daysBetween(oldDate, newDate);

2 个答案:

答案 0 :(得分:2)

试试days.getDays()。根据{{​​1}}中size()的{​​{3}}(BaseSingleFieldPeriod的超级类}:

  

获取此期间支持的字段数,即1。

答案 1 :(得分:0)

以毫秒为单位转换两天,并以毫秒为单位获取它们之间的差异,并将差异除以(24 * 60 * 60 * 1000)以获取两个日历日期之间的天差

示例

void getDiff(){
    Calendar calendar1 = Calendar.getInstance();
      Calendar calendar2 = Calendar.getInstance();
      calendar1.set(2011, 01, 10);
      calendar2.set(2011, 03, 01);
     long milliseconds1 = calendar1.getTimeInMillis();
      long milliseconds2 = calendar2.getTimeInMillis();
      long diff = milliseconds2 - milliseconds1;
       long diffDays = diff / (24 * 60 * 60 * 1000);
       System.out.println("...Difference in days..."+diffDays);
}