Java日期差异的天数

时间:2015-09-22 09:04:29

标签: java date

有没有人可以帮助我以有效的方式计算Date天数方面的差异?

Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;

4 个答案:

答案 0 :(得分:6)

//diff in msec
long diff = currentDate.getTime() - nextCollectionDate.getTime();

//diff in days
long days = diff / (24 * 60 * 60 * 1000);

答案 1 :(得分:3)

您可以使用JodaTime这是一个非常有用的API用于这些场景

int days = Days.daysBetween(date1, date2).getDays();

或者你可以创建自己的方法并获得差异

public long getDays(Date d1, Date d2) 
{
    long l = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}

答案 2 :(得分:2)

我建议你在Java 8中使用LocalDate

LocalDate startDate = LocalDate.now().minusDays(1);
LocalDate endDate = LocalDate.now();
long days = Period.between(startDate, endDate).getDays();
System.out.println("No of days: " + days);

按预期打印:

No of days: 1

答案 3 :(得分:1)

你可以使用joda api

下面的代码应解决您的查询

 Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
    Date currentDate = new Date();
    Days  d = Days.daysBetween(new DateTime(nextCollectionDate ), new DateTime(currentDate ))

    int daysDiff = d.getDays();