I'm trying to find out the difference between two date objects. I need to know if the time between them is greater than 5 years. Is there a simple way to do this. The first date will always be the system time (today), and the second date will be a date I'm retrieving from the database... the day it was inserted into the database. Both objects are of java.util.Date type.
You can get a long value from a date or calendar that is the number of milliseconds since January 1, 1970 00:00:00.000 GMT (Gregorian). Subtracting one date from another will give you a fairly big number. You can try some math on that:
You could also get month, day and year and do some stuff like:
It's been years since I've done that, forgot how ugly it is.
Anyhow, does that give you any ideas? [ October 05, 2005: Message edited by: Stan James ]
A good question is never answered. It is not a bolt to be tightened into place but a seed to be planted and to bear more seed toward the hope of greening the landscape of the idea. John Ciardi
Checking the number of milliseconds between the two dates runs into problems when the dates are close to 5 yrs apart, because the number of milliseconds in 5 yrs depends on how many leap years are included.
A better approach is to subtract 5 years from the current date, and then compare the result to the other date (which Calendar.compareTo does by comparing milliseconds).
BTW, have you clearly defined the boundary? Is it based on date and time, or just date? For example, a date and time comparison makes 2pm Jan 10 2000 more than 5 years before 3pm Jan 10 1005, but in many real-world applications (like have you owned a car for more than 5 years) you need to go back to Jan 9 2000 before you are considered to be more than 5 years before Jan 10 2005.