0

How to get difference between current date and other date ( java.util.Date) in years in Java

I have incoming java.util.Date object and I need to get how many whole years are between them.

I tried Joda's time Period but I have to create joda's time object. Is there other way to calculate this difference. Way to get millis and try to convert it to years doesn't count leap years.

Constantine Gladky
  • 1,245
  • 6
  • 27
  • 45

4 Answers4

7

Since most of the methods in the Date class are deprecated, you can use java.util.Calendar.

Calendar firstCalendar = Calendar.getInstance();
firstCalendar.setTime(firstDate); //set the time as the first java.util.Date

Calendar secondCalendar = Calender.getInstance();
secondCalendar.setTime(secondDate); //set the time as the second java.util.Date

int year = Calendar.YEAR;
int month = Calendar.MONTH;
int difference = secondCalendar.get(year) - firstCalendar.get(year);
if (difference > 0 && 
    (secondCalendar.get(month) < firstCalendar.get(month))) {
    difference--;
} 

With the if statement I'm checking if we have dates like June, 2011 and March, 2012 (for which the whole year difference would be 0). Of course, I'm assuming that secondDate is after firstDate.

Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
2

Starting with JDK 8, you can get a Duration between 2 dates. Even better, some ChronoUnits, like years, as you requested.

Instant t1, t2;
...
long years = ChronoUnit.YEARS.between(t1, t2);

Forget about Date, 3rd party jars(Joda Time is cool, but let's do it in a standard way) and Calendars. JDK 8 is the future.

Embrace it ! http://docs.oracle.com/javase/tutorial/datetime/iso/period.html

Silviu Burcea
  • 5,103
  • 1
  • 29
  • 43
1

I'd recommend using joda.

DateTime start = new DateTime(a);  
DateTime end = new DateTime(b); 
difference = Years.yearsBetween(start, end).getYears();
Ben
  • 391
  • 5
  • 13
0

Convert a java.util.Date to a org.joda.time.DateTime object is trivial, because DateTime has a constructor for this:

 DateTime jodaTime = new DateTime(javaDate);

You can then pass these to org.joda.time.Period and call getYears() on the result to get the number of whole years between these two dates:

 public int getYearDifference (Date begin, Date end) {
     return new Period(new DateTime(begin), new DateTime(end)).getYears();  
 }
Philipp
  • 67,764
  • 9
  • 118
  • 153