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.