getting the difference between date in days in java [duplicate]

Possible Duplicate:
how to calculate difference between two dates using java

I'm trying something like this, where I'm trying to get the date from comboboxes

Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();  

int Sdate=Integer.parseInt(cmbSdate.getSelectedItem().toString());  
int Smonth=cmbSmonth.getSelectedIndex();
int Syear=Integer.parseInt(cmbSyear.getSelectedItem().toString());  

int Edate=Integer.parseInt(cmbEdate.getSelectedItem().toString());
int Emonth=cmbEmonth.getSelectedIndex();
int Eyear=Integer.parseInt(cmbEyear.getSelectedItem().toString());

start.set(Syear,Smonth,Sdate);  
end.set(Eyear,Emonth,Edate);

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");
String startdate=dateFormat.format(start.getTime());  
String enddate=dateFormat.format(end.getTime());

I'm not able to subtract the end and start date How do I get the difference between the start date and end date??


Calendar start = Calendar.getInstance();
Calendar end = Calendar.getInstance();
start.set(2010, 7, 23);
end.set(2010, 8, 26);
Date startDate = start.getTime();
Date endDate = end.getTime();
long startTime = startDate.getTime();
long endTime = endDate.getTime();
long diffTime = endTime - startTime;
long diffDays = diffTime / (1000 * 60 * 60 * 24);
DateFormat dateFormat = DateFormat.getDateInstance();
System.out.println("The difference between "+
  dateFormat.format(startDate)+" and "+
  dateFormat.format(endDate)+" is "+
  diffDays+" days.");

This will not work when crossing daylight savings time (or leap seconds) as orange80 pointed out and might as well not give the expected results when using different times of day. Using JodaTime might be easier for correct results, as the only correct way with plain Java before 8 I know is to use Calendar's add and before/after methods to check and adjust the calculation:

start.add(Calendar.DAY_OF_MONTH, (int)diffDays);
while (start.before(end)) {
    start.add(Calendar.DAY_OF_MONTH, 1);
    diffDays++;
}
while (start.after(end)) {
    start.add(Calendar.DAY_OF_MONTH, -1);
    diffDays--;
}

Use JodaTime for this. It is much better than the standard Java DateTime Apis. Here is the code in JodaTime for calculating difference in days:

private static void dateDiff() {

    System.out.println("Calculate difference between two dates");
    System.out.println("=================================================================");

    DateTime startDate = new DateTime(2000, 1, 19, 0, 0, 0, 0);
    DateTime endDate = new DateTime();

    Days d = Days.daysBetween(startDate, endDate);
    int days = d.getDays();

    System.out.println("  Difference between " + endDate);
    System.out.println("  and " + startDate + " is " + days + " days.");

  }