How to get number of days between two calendar instance?

Akram picture Akram · Oct 19, 2013 · Viewed 53.4k times · Source

I want to find the difference between two Calendar objects in number of days if there is date change like If clock ticked from 23:59-0:00 there should be a day difference.

i wrote this

public static int daysBetween(Calendar startDate, Calendar endDate) {  
    return Math.abs(startDate.get(Calendar.DAY_OF_MONTH)-endDate.get(Calendar.DAY_OF_MONTH));  
} 

but its not working as it only gives difference between days if there is month difference its worthless.

Answer

Jk1 picture Jk1 · Oct 19, 2013

Try the following approach:

public static long daysBetween(Calendar startDate, Calendar endDate) {
    long end = endDate.getTimeInMillis();
    long start = startDate.getTimeInMillis();
    return TimeUnit.MILLISECONDS.toDays(Math.abs(end - start));
}