Difference in days between two dates in Java?

Venkat picture Venkat · Jul 21, 2010 · Viewed 192.9k times · Source

I need to find the number of days between two dates: one is from a report and one is the current date. My snippet:

  int age=calculateDifference(agingDate, today);

Here calculateDifference is a private method, agingDate and today are Date objects, just for your clarification. I've followed two articles from a Java forum, Thread 1 / Thread 2.

It works fine in a standalone program although when I include this into my logic to read from the report I get an unusual difference in values.

Why is it happening and how can I fix it?

EDIT :

I'm getting a greater number of days compared to the actual amount of Days.

public static int calculateDifference(Date a, Date b)
{
    int tempDifference = 0;
    int difference = 0;
    Calendar earlier = Calendar.getInstance();
    Calendar later = Calendar.getInstance();

    if (a.compareTo(b) < 0)
    {
        earlier.setTime(a);
        later.setTime(b);
    }
    else
    {
        earlier.setTime(b);
        later.setTime(a);
    }

    while (earlier.get(Calendar.YEAR) != later.get(Calendar.YEAR))
    {
        tempDifference = 365 * (later.get(Calendar.YEAR) - earlier.get(Calendar.YEAR));
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    if (earlier.get(Calendar.DAY_OF_YEAR) != later.get(Calendar.DAY_OF_YEAR))
    {
        tempDifference = later.get(Calendar.DAY_OF_YEAR) - earlier.get(Calendar.DAY_OF_YEAR);
        difference += tempDifference;

        earlier.add(Calendar.DAY_OF_YEAR, tempDifference);
    }

    return difference;
}

Note :

Unfortunately, none of the answers helped me solve the problem. I've accomplished this problem with the help of Joda-time library.

Answer

Adam Schmideg picture Adam Schmideg · Jul 21, 2010

I would suggest you use the excellent Joda Time library instead of the flawed java.util.Date and friends. You could simply write

import java.util.Date;
import org.joda.time.DateTime;
import org.joda.time.Days;

Date past = new Date(110, 5, 20); // June 20th, 2010
Date today = new Date(110, 6, 24); // July 24th 
int days = Days.daysBetween(new DateTime(past), new DateTime(today)).getDays(); // => 34