Win a copy of Mesos in Action this week in the Cloud/Virtualizaton forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

Dates difference between them

 
Adrian Enns
Ranch Hand
Posts: 48
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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 ]
 
Kenneth Albertson
Ranch Hand
Posts: 59
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
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
Posts: 225
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
You can use Calendar's add method.
(add 5 years to the oldest date, and compare it to the newest one)
 
Stan James
(instanceof Sidekick)
Ranch Hand
Posts: 8791
  • Mark post as helpful
  • send pies
  • Quote
  • Report post to moderator
Oh, man, I look so stoopid! Thanks!
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic