以天为单位的Java日期差异

以天为单位的Java日期差异,java,date,Java,Date,有谁能帮我以有效的方式计算日期天数差异吗 Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate(); Date currentDate = new Date(); int daysDiff = currentDate - nextCollectionDate; 对于这些场景,您可以使用非常有用的API int days = Days.daysBetween(date1, date2).get

有谁能帮我以有效的方式计算
日期
天数差异吗

Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;
对于这些场景,您可以使用非常有用的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);
}
您可以使用JodaAPI

下面的代码应该可以解决您的查询

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

    int daysDiff = d.getDays();

我建议您在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

你到底期望什么?你得到了什么?问题是什么?我想计算两个日期之间的天数差。使用Java 8的时间API、JodaTime甚至日历。另一个选项是使用
No of days: 1