Get the days difference in Java
Description
The following code shows how to get the days difference.
Example
//from w w w . j ava2s . c om
import java.util.Calendar;
import java.util.Date;
public class Main {
public final static long SECOND_MILLIS = 1000;
public final static long MINUTE_MILLIS = SECOND_MILLIS * 60;
public final static long HOUR_MILLIS = MINUTE_MILLIS * 60;
public final static long DAY_MILLIS = HOUR_MILLIS * 24;
/**
* Get the days difference
*/
public static int daysDiff(Date earlierDate, Date laterDate) {
if (earlierDate == null || laterDate == null)
return 0;
return (int) ((laterDate.getTime() / DAY_MILLIS) - (earlierDate.getTime() / DAY_MILLIS));
}
public static void main(String[] argv) {
Date date1 = Calendar.getInstance().getTime();
Calendar cal = Calendar.getInstance();
cal.set(2010, 10, 10);
Date date2 = cal.getTime();
System.out.println(daysDiff(date1, date2));
}
}
The code above generates the following result.