一尘不染

Java中两个日期之间的天数差异?

java

我需要找到两个日期之间的天数:一个是来自报表,另一个是当前日期。我的片段:

  int age=calculateDifference(agingDate, today);

calculateDifference是一个私有方法,agingDate并且today是Date对象,仅供您说明。我关注了Java论坛中的两篇文章Thread 1 / Thread 2。

它在独立程序中可以正常工作,尽管当我将其包含在逻辑中以从报告中读取时,我会在值上获得不同寻常的区别。

为什么会发生,如何解决?

编辑:

与实际天数相比,我得到的天数更多。

public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}

阅读 524

收藏
2020-03-01

共1个答案

一尘不染

我建议您使用出色的Joda Time库,而不要使用有缺陷的java.util.Date和朋友。你可以简单地写

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010
Date today = new Date(110, 6, 24); // July 24th 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34
2020-03-01