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!

How many days between two date 1

Status
Not open for further replies.

hksr

MIS
Sep 26, 2003
30
HK
In the jsp, I would like to calculate the number of days between two days. What is the function I use and what is the import package?
 
Suppose you have two Date objects, say startDate and endDate, you can then calculate the number of days between them by:

(startDate.getTime() - endDate.getTime)/(1000*60*60*24)
 
This is a common way but there is an important point that must be considered.
If your Date objects' timestamps are initialized, this method may give you wrong result.

Here is an example
startDate -- > 20 NOV 2003 02.00
endDate -- > 19 NOV 2003 23.59

then (startDate.getTime() - endDate.getTime)/(1000*60*60*24)
will give you 0 not 1.

If you are not going to set the time fields (then the time values will be 00:00:00) there is no problem but if your are setting the time values, then you have to think of a method that overcomes this sort problem.

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
Good point Salih. I re-arranged the calculation, this should fix the problem:

endDate.getTime()/(1000*60*60*24) - startDate.getTime()/(1000*60*60*24);
 
Yes your solution completely solves the problem.Here is a star from Istanbul Turkey to you [wavey2]

Salih Sipahi
Software Engineer.
City of Istanbul Turkey
s.sipahi@sahinlerholding.com.tr
turkey_clr.gif
 
How Can I convert a string to the date object?
Can you give me some coding example?
 
Hi,

You can use SimpleDateFormat and you can specify the String format.

Try this,

String raw = "1998-06-03";
SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
java.util.Date dt = new java.util.Date();
try {
dt = format.parse(raw);
} catch (ParseException ex) {

}

Cheers,
Venu
 
Status
Not open for further replies.

Part and Inventory Search

Sponsor

Back
Top