Re: How do I compare 2 dates that the user enters and return the number of days in between?
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
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.