Here is a portion of an
applet assignment I gave my students to help them calculate the number of days between two dates using J++. It should give you some ideas:
Create a class named MyCalendar that extends GregorianCalendar for the purpose of accessing the protected getTimeInMillis( ) method. The code for this class is as follows:
import java.util.*;
public class MyCalendar extends GregorianCalendar
{
public MyCalendar()
{
super();
}
public long toMillis()
{
return getTimeInMillis();
}
}
To calculate and display information about a particular date in the future or in the past (as far back as January 1, 1970), your applet must contain a text field in which the user may enter the target date as a
String in English. You will need to convert this String to a MyCalendar object in order to perform date processing. For example, the following code could be used (assuming the reference of the text field object is targetDateField):
DateFormat localDate = DateFormat.getDateInstance(DateFormat.SHORT,Locale.US);
MyCalendar targetDate = new MyCalendar();
try
{
targetDate.setTime(localDate.parse(targetDateField.getText().trim()));
}
catch (ParseException err)
{
}
This permits the date string to be entered in MM/DD/YYYY format (such as "10/15/1978"). The try and catch are needed to satisfy the compiler.
Calculating the number of days between two dates can be challenging when they are in different years. To do so, you need to convert each date into milliseconds, subtract to obtain their difference in milliseconds, then divide the result by the number of milliseconds in one day ( 24*60*60*1000 ). Be sure to use the toMillis( ) method of MyCalendar.
Hope this helps...