我该如何正确比较两个日期?

时间:2013-04-17 15:16:40

标签: java date-comparison

在实施这项简单任务时遇到一些麻烦。

基本上我想比较两个日期(一些旧日期与新日期)。我想知道更旧的日期是否超过x个月和y天。

int monthDiff = new Date().getMonth() - detail.getCdLastUpdate().getMonth();
int dayDiff = new Date().getDay() - detail.getCdLastUpdate().getMonth();
System.out.println("\tthe last update date and new date month diff is --> " + monthDiff);
System.out.println("\tthe last update date and new date day diff is --> " + dayDiff);

如果旧日期是2012-09-21 00:00:00.0,那么它将返回负数。我需要查看旧日期是否恰好在新日期()之前6个月和4天。我正在考虑使用两者的绝对值,但今天不能大脑。

编辑:我知道joda,但我无法使用它。我必须使用Java JDK。 编辑2:我将尝试列出的方法,如果全部失败,我将使用Joda。

3 个答案:

答案 0 :(得分:6)

JDK dates有方法之前和之后,返回布尔值来完成你的任务:

Date now = new Date();
Calendar compareTo = Calendar.getInstance();
compareTo.add(Calendar.MONTH, -6);
compareTo.add(Calendar.DATE, -4);
if (compareTo.getTime().before(now)) {
   // after
} else {
   // before or equal 
}

答案 1 :(得分:5)

我能想到的最好方法是使用Joda-Time library。他们网站的例子:

Days d = Days.daysBetween(startDate, endDate);
int days = d.getDays();

或月数:

Months m = Months.monthsBetween(startDate, endDate)
int months = m.getMonths();

其中:

DateTime startDate =  new DateTime(/*jdk Date*/);
DateTime endDate =  new DateTime(/*jdk Date*/);

答案 2 :(得分:3)

叹息,由我来添加不可避免的“使用JodaTime”答案。

JodaTime为您提供了所有重要时间距离的特定数据类型。

Date yourReferenceDate = // get date from somewhere
int months = Months.monthsBetween(
                       new DateTime(yourReferenceDate),
                       DateTime.now()
             ).getMonths();
相关问题