How do I compare 2 dates that the user enters and return the number of days in between?
1 posts in topic
Flat View  Flat View
TOPIC ACTIONS:
 

Posted By:   Paul_Hyland
Posted On:   Friday, March 7, 2003 04:14 AM


Have a project that lets users rent equipment for dates specified by them, in order to work out the price payable i need a method that returns the number of days between the dates entered. Found little in the API. Any thoughts would be much appreciated??

Re: How do I compare 2 dates that the user enters and return the number of days in between?

Posted By:   Bahman_Barzideh  
Posted On:   Friday, March 7, 2003 05:30 AM

I would suggest abusing the Date class. You can create a Date object from each date. Convert each object to a long by calling the getTime () method of Date.
Subtract the two longs and divide the results by the number of
milliseconds in a day. This will give you the # of days. You may, of couse, have to deal with fraction of days.



An item to consider is how to create the Date objects. If your input is
a single string you can use the DateFormat class to parse
the string into a Date object. If the date is already parsed out (for
example you have 3 fields on the screen from which the user is selecting
the year, month and day), you can instantiate a
GregorianCalendar object, populate it with the values you
have and then call the getTime () method to get a Date
class or (in java 1.4) call the getTimeInMillis () method to get the longs
directly.



This all assumes you are interested in the # of calendar days not work
days and you don't need to distinguish work days from holidays. If you
need that level of sophistication, I would suggest looking at the Calendar class.
About | Sitemap | Contact