4

Could anyone please help me out for calculating Date difference in terms of no of days in an efficient way?

Date nextCollectionDate = dispenseNormal.getDispensing().getNextCollectionDate();
Date currentDate = new Date();
int daysDiff = currentDate - nextCollectionDate;
Shine
  • 3,788
  • 1
  • 36
  • 59
Arvind Chavhan
  • 488
  • 1
  • 6
  • 14

4 Answers4

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

//diff in days
long days = diff / (24 * 60 * 60 * 1000);
Shine
  • 3,788
  • 1
  • 36
  • 59
3

You can use JodaTime which is a very useful API for these scenarios

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

or else you can create your own method and get the difference

public long getDays(Date d1, Date d2) 
{
    long l = d2.getTime() - d1.getTime();
    return TimeUnit.DAYS.convert(l, TimeUnit.MILLISECONDS);
}
Rahul Tripathi
  • 168,305
  • 31
  • 280
  • 331
2

I would suggest you to use LocalDate in Java 8:

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

which as expected will print:

No of days: 1
akhil_mittal
  • 23,309
  • 7
  • 96
  • 95
1

You can use joda api

Below code should solve your query

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

    int daysDiff = d.getDays();
M S Parmar
  • 955
  • 8
  • 22