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

问题描述:

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

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDifference(agingDate, today);

这里的calculateDifference 是一个私有方法,agingDatetodayDate 对象,仅供您说明.我关注了 Java 论坛上的两篇文章,Thread 1/主题 2.

Here calculateDifference is a private method, agingDate and today are Date objects, just for your clarification. I've followed two articles from a Java forum, Thread 1 / Thread 2.

它在独立程序中运行良好,尽管当我将其包含到我的逻辑中以从报告中读取时,我得到了不寻常的值差异.

It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values.

为什么会发生这种情况,我该如何解决?

Why is it happening and how can I fix it?

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

I'm getting a greater number of days compared to the actual amount of Days.

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;
}

注意:

不幸的是,没有一个答案能帮助我解决问题.我在 这个问题"http://sourceforge.net/projects/joda-time/files/joda-time/" rel="nofollow noreferrer">Joda-time 库.

Unfortunately, none of the answers helped me solve the problem. I've accomplished this problem with the help of Joda-time library.

我建议你使用优秀的 Joda Time 库而不是有缺陷的 java.util.Date 和朋友.你可以简单地写

I would suggest you use the excellent Joda Time library instead of the flawed java.util.Date and friends. You could simply write

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