How to subtract dates to get days/hrs/mins/secs when java does not allow su
subtraction like this
java.util.Date DateOne;
java.util.Date DateTwo;
String difference = "";
difference = DateOne - DateTwo;
Does anyone out there have some sample code for this. Seems like its a pretty simple thing, its just taking me for a whirl.
Thanks
[306 byte] By [
adamrau] at [2007-9-26 3:03:13]

Dates are handled in milliseconds, what I did is to form the two dates, get the millisecond values, substract them and with the resulting long millisecond value construct a new date. Ylan
This is incorrect! All you will end up with is some new Date that is the amount of milliseconds since 1 Jan 1970.You have to use the Calendar object, and then extract out (painfully) weach field and do the subtracting operation on each of the fields.
final long MS_IN_A_DAY = 1000*60*60*24;
final long MS_IN_AN_HOUR = 1000*60*60;
final long MS_IN_A_MINUTE = 1000*60;
final long MS_IN_A_SECOND = 1000;
java.util.Date date1;
java.util.Date date2;
long diff = date1.getTime() - date2.getTime();
long numDays = diff/MS_IN_A_DAY;
diff = diff%MS_IN_A_DAY;
long numHours = diff/MS_IN_AN_HOUR;
diff = diff%MS_IN_AN_HOUR;
long numMinutes = diff/MS_IN_A_MINUTE;
diff = diff%MS_IN_A_MINUTE;
long numSeconds = diff/MS_IN_A_SECOND;
diff = diff%MS_IN_A_SECOND;
long numMilliseconds = diff;
String result = numDays + " days, " + numHours + " hours, " + numMinutes + " minutes, " + numSeconds + " seconds, " + numMilliseconds + " ms";