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

2022-08-31 12:24:39

我需要查找两个日期之间的天数:一个来自报告,另一个是当前日期。我的代码段:

  int age=calculateDifference(agingDate, today);

这是一个私有方法,并且是对象,只是为了您的澄清。我关注了Java论坛的两篇文章,线程1 / 线程2calculateDifferenceagingDatetodayDate

它在独立程序中工作正常,尽管当我将其包含在我的逻辑中以从报告中读取时,我得到了一个不寻常的值差异。

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

编辑:

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

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

注意:

不幸的是,没有一个答案帮助我解决问题。我在Joda-time图书馆的帮助下完成了这个问题


答案 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

答案 2

我可能来不及加入游戏,但到底是什么?:)

你认为这是一个线程问题吗?例如,您如何使用此方法的输出?或

我们可以更改您的代码以执行以下简单操作吗:

Calendar calendar1 = Calendar.getInstance();
    Calendar calendar2 = Calendar.getInstance();
    calendar1.set(<your earlier date>);
    calendar2.set(<your current date>);
    long milliseconds1 = calendar1.getTimeInMillis();
    long milliseconds2 = calendar2.getTimeInMillis();
    long diff = milliseconds2 - milliseconds1;
    long diffSeconds = diff / 1000;
    long diffMinutes = diff / (60 * 1000);
    long diffHours = diff / (60 * 60 * 1000);
    long diffDays = diff / (24 * 60 * 60 * 1000);
    System.out.println("\nThe Date Different Example");
    System.out.println("Time in milliseconds: " + diff
 + " milliseconds.");
    System.out.println("Time in seconds: " + diffSeconds
 + " seconds.");
    System.out.println("Time in minutes: " + diffMinutes 
+ " minutes.");
    System.out.println("Time in hours: " + diffHours 
+ " hours.");
    System.out.println("Time in days: " + diffDays 
+ " days.");
  }

推荐