public static int getNumberOfDays ( Date first , Date second ) { Calendar c = Calendar . getInstance ( ) ; int result = 0 ; int compare = first . compareTo ( second ) ; if ( compare > 0 ) return 0 ; if ( compare == 0 ) return 1 ; c . setTime ( first ) ; int firstDay = c . get ( Calendar . DAY_OF_YEAR ) ; int firstYear = c . get ( Calendar . YEAR ) ; int firstDays = c . getActualMaximum ( Calendar . DAY_OF_YEAR ) ; c . setTime ( second ) ; int secondDay = c . get ( Calendar . DAY_OF_YEAR ) ; int secondYear = c . get ( Calendar . YEAR ) ; // if dates in the same year if ( firstYear == secondYear ) { result = secondDay - firstDay + 1 ; } // different years else { // days from the first year result += firstDays - firstDay + 1 ; // add days from all years between the two dates years for ( int i = firstYear + 1 ; i < secondYear ; i ++ ) { c . set ( i , 0 , 0 ) ; result += c . getActualMaximum ( Calendar . DAY_OF_YEAR ) ; } // days from last year result += secondDay ; } return result ; }
Get number of days between two dates