2

I want to calculate the difference between two dates. Currently, I am doing:

Calendar firstDate = Calendar.getInstance();
firstDate.set(Calendar.DATE, 15);
firstDate.set(Calendar.MONTH, 4);
firstDate.get(Calendar.YEAR);

int diff = (new Date().getTime - firstDate.getTime)/(1000 * 60 * 60 * 24)

This gives me output 0. But I want that I should get the output 0 when the new Date() is 15. Currently the new date is 14. It makes my further calculation wrong and I am confused how to resolve this. Please suggest.

Andrew Thompson
  • 168,117
  • 40
  • 217
  • 433
Mohit224
  • 443
  • 1
  • 10
  • 24

2 Answers2

3

Finding the difference between two dates isn't as straightforward as subtracting the two dates and dividing the result by (24 * 60 * 60 * 1000). Infact, its erroneous!

/* Using Calendar - THE CORRECT (& Faster) WAY**/  
//assert: startDate must be before endDate  
public static long daysBetween(final Calendar startDate, final Calendar endDate) {  
 int MILLIS_IN_DAY = 1000 * 60 * 60 * 24;  
 long endInstant = endDate.getTimeInMillis();  
 int presumedDays = (int) ((endInstant - startDate.getTimeInMillis()) / MILLIS_IN_DAY);  
 Calendar cursor = (Calendar) startDate.clone();  
 cursor.add(Calendar.DAY_OF_YEAR, presumedDays);  
 long instant = cursor.getTimeInMillis();  
 if (instant == endInstant)  
  return presumedDays;  
 final int step = instant < endInstant ? 1 : -1;  
 do {  
  cursor.add(Calendar.DAY_OF_MONTH, step);  
  presumedDays += step;  
 } while (cursor.getTimeInMillis() != endInstant);  
 return presumedDays;  
}  

You can read more on this here.

pacman
  • 1,061
  • 1
  • 17
  • 36
1

I don't think that by creating a new Date() will give you the current time and date instead do this:

Calendar cal = Calendar.getInstance();
Date currentDate = cal.getTime();
Date firstDate = new Date();
firstDate.setHour(...);
firstDate.setMinute(...);
firstDate.setSeconds(...);

long dif = currentDate.getTime() - firstDate.getTime();

So as you can see you can be as straightforward as subtracting one from another...

Alexandru Chirila
  • 2,274
  • 5
  • 29
  • 40