File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes Dates difference between them Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "Dates difference between them" Watch "Dates difference between them" New topic
Author

Dates difference between them

Adrian Enns
Ranch Hand

Joined: Aug 11, 2004
Posts: 48
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.
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
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
Kenneth Albertson
Ranch Hand

Joined: Sep 18, 2005
Posts: 59
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.
Seb Mathe
Ranch Hand

Joined: Sep 28, 2005
Posts: 225
You can use Calendar's add method.
(add 5 years to the oldest date, and compare it to the newest one)


Regards,<br />Seb<br /> <br />SCJP 1.4
Stan James
(instanceof Sidekick)
Ranch Hand

Joined: Jan 29, 2003
Posts: 8791
Oh, man, I look so stoopid! Thanks!
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: Dates difference between them