How to get the number of years between two java.util.Date? Note: using only java.util.Date...
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);
Use the getTime method for each Date object and do the subtraction. Convert the result to years.
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.
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.