java date + calendar problem
Hello to All,
I'm developing a server-side application has a part, which counts users expiry.
I'm using the following method to count the days between the expiry date (toSubtract) and the current date (returned by getStartDate()):
/**
* Subtract a date of a given Date from the start date.
* Returns number of days. It is positive if date is due.
*/
public int subtractDate(Date toSubtract) throws FrwException {
TRACER.traceEnter("TimeAccess.subtractDate(", toSubtract);
Calendar s = new GregorianCalendar();
TimeZone z = TimeZone.getTimeZone("UTC");
s.setTime(getStartDate());
int y1 = s.get(Calendar.YEAR);
int m1 = s.get(Calendar.MONTH);
int d1 = s.get(Calendar.DAY_OF_MONTH);
s.clear();
s.setTimeZone(z);
s.set(y1, m1, d1);
long now = s.getTime().getTime();
s.setTime(toSubtract);
int y2 = s.get(Calendar.YEAR);
int m2 = s.get(Calendar.MONTH);
int d2 = s.get(Calendar.DAY_OF_MONTH);
s.clear();
s.setTimeZone(z);
s.set(y2, m2, d2);
long t = s.getTime().getTime();
int result = (int)((now - t) / ONE_DAY);
TRACER.traceReturn("TimeAccess.subtractDate()", result);
return result;
}
I invoke the method a lot of times and check whether the returned value is greater than zero.
The algorithm works perfect excludes the following mysterious case:
if startDate is YYYY-MM-DD and toSubtract is YYYY-(MM+2)-(DD-2), the algorithm returns a positive value, which is false in my opinion.
Is there any conversion problem I did't thought about?
The platform is java 1.4.2_07-b05 on Sun Solaris
Thanks for your help in advance!
Best regards,
Balazs

