Tek-Tips is the largest IT community on the Internet today!

Members share and learn making Tek-Tips Forums the best source of peer-reviewed technical information on the Internet!

  • Congratulations IamaSherpa on being selected by the Tek-Tips community for having the most helpful posts in the forums last week. Way to Go!

JSP ~ Date duration????

Status
Not open for further replies.

hydee

Technical User
Mar 2, 2002
1
IE
Hi there,

I am desperate to find out how I can take two dates entered by a user and from these dates find out the number of days between them?
e.g. 2/03/2002 (this is a start date)
9/03/2002 (this is an end date)
I need to know how many days are between these?

Thanks
 
First set the dates into a calendar format

Calendar calA = Calendar.getInstance();
Calendar calB = Calendar.getInstance();

calA.set(year.intValue(),(month.intValue() - 1),day.intValue());
calB.set(year2.intValue(),(month2.intValue() - 1),day2.intValue());

to get the year, month and day values out of a string you could try using the StringTokenizer class. the doc for it can be found here:


Once the calendar variables have been set use the following function to return the number of days

System.out.prinltn("The number of days difference is "+ dayDifference(calA, calB));

public long dayDifference(Calendar c1, Calendar c2){
//c1.clear(c1.MILLISECOND);
//c2.clear(c2.MILLISECOND);
long millisecs = c1.getTime().getTime() - c2.getTime().getTime();
long remainder = millisecs % 86400000;
long days = (millisecs - remainder) / 86400000;

return days;
}
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top