[java] How do you subtract Dates in Java?

My heart is bleeding internally after having to go so deep to subtract two dates to calculate the span in number of days:

    GregorianCalendar c1 = new GregorianCalendar();
    GregorianCalendar c2 = new GregorianCalendar();
    c1.set(2000, 1, 1);
    c2.set(2010,1, 1);
    long span = c2.getTimeInMillis() - c1.getTimeInMillis();
    GregorianCalendar c3 = new GregorianCalendar();
    c3.setTimeInMillis(span);
    long numberOfMSInADay = 1000*60*60*24;
    System.out.println(c3.getTimeInMillis() / numberOfMSInADay); //3653

where it's only 2 lines of code in .NET, or any modern language you name.

Is this atrocious of java? Or is there a hidden method I should know?

Instead of using GregorianCalendar, is it okay to use Date class in util? If so, should I watch out for subtle things like the year 1970?

Thanks

This question is related to java datetime

The answer is


If you deal with dates it is a good idea to look at the joda time library for a more sane Date manipulation model.

http://joda-time.sourceforge.net/


You can use the following approach:

SimpleDateFormat formater=new SimpleDateFormat("yyyy-MM-dd");

long d1=formater.parse("2001-1-1").getTime();
long d2=formater.parse("2001-1-2").getTime();

System.out.println(Math.abs((d1-d2)/(1000*60*60*24)));

Here's the basic approach,

DateFormat dateFormat = new SimpleDateFormat("yyyy-MM-dd");

Date beginDate = dateFormat.parse("2013-11-29");
Date endDate = dateFormat.parse("2013-12-4");

Calendar beginCalendar = Calendar.getInstance();
beginCalendar.setTime(beginDate);

Calendar endCalendar = Calendar.getInstance();
endCalendar.setTime(endDate);

There is simple way to implement it. We can use Calendar.add method with loop. The minus days between beginDate and endDate, and the implemented code as below,

int minusDays = 0;
while (true) {
  minusDays++;

  // Day increasing by 1
  beginCalendar.add(Calendar.DAY_OF_MONTH, 1);

  if (dateFormat.format(beginCalendar.getTime()).
            equals(dateFormat.format(endCalendar).getTime())) {
    break;
  }
}
System.out.println("The subtraction between two days is " + (minusDays + 1));**

Well you can remove the third calendar instance.

GregorianCalendar c1 = new GregorianCalendar();
GregorianCalendar c2 = new GregorianCalendar();
c1.set(2000, 1, 1);
c2.set(2010,1, 1);
c2.add(GregorianCalendar.MILLISECOND, -1 * c1.getTimeInMillis());