tags:

views:

1523

answers:

4

How to get the number of years between two java.util.Date? Note: using only java.util.Date...

+9  A: 

How accurate do you need to be? If approximate is good enough, then I'd do

long msDiff = date1.getTime() - date2.getTime();
int yearDiff = (int)(msDiff / 1000 / 60 / 60 / 24 / 365.25);
Paul Tomblin
that wont compile - you will need an explicit cast to int.
toolkit
Right. I'll fix that.
Paul Tomblin
+1 (modulo the cast) - using just java.util.Date you won't get more accurate without duplicating a bunch of GregorianCalendar.
Ken Gentle
This is not correct for leap years as the year 1900 was not a leap year (being devidable by 100, but 2000 was as it is devidable with 400)
Drejc
@Drejc - this code doesn't attempt to compensate for leap years at all.
Paul Tomblin
A: 

Use the getTime method for each Date object and do the subtraction. Convert the result to years.

kgiannakakis
+1  A: 

Do you really need to use java.util.Date??

If you would relax this constrain and allow usage of Joda Time - Java date and time API you could have your task done like that:

import org.joda.time.DateTime;
import org.joda.time.Period;

import static java.lang.System.out;

public class App {
  public static void main(String[] args) {
    final DateTime now = new DateTime();
    out.println(new Period(now.minusYears(2), now).getYears());
    out.println(new Period(now.minusYears(2).plusHours(1), now).getYears());
  }
}

Output result is:

2
1

If you can't use Joda Time use java.util.Calendar.

Hubert
A: 

I assume, since this question is tagged under GWT, that you are trying to do date math in a GWT application. GWT's emulation library implements the depricated function Date.getYear(), in which case you can just do date2.getYear() - date1.getYear().

Using depricated functions isn't the best, but appears to be common practice in the GWT development world.