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

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??

This question is related to java date

The answer is


Like this.

import java.util.Date;
import java.util.GregorianCalendar;

/**
 * DateDiff -- compute the difference between two dates.
 */
public class DateDiff {
  public static void main(String[] av) {
    /** The date at the end of the last century */
    Date d1 = new GregorianCalendar(2000, 11, 31, 23, 59).getTime();

    /** Today's date */
    Date today = new Date();

    // Get msec from each, and subtract.
    long diff = today.getTime() - d1.getTime();

    System.out.println("The 21st century (up to " + today + ") is "
        + (diff / (1000 * 60 * 60 * 24)) + " days old.");
  }

}

Here is an article on Java date arithmetic.


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.");

  }