import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || 
        (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

Note: as Ole V.V. noticed, this won't work with dates before Christ due how Calendar works.

Answer from sinuhepop on Stack Overflow
🌐
Baeldung
baeldung.com › home › java › java dates › difference between two dates in java
Difference Between Two Dates in Java | Baeldung
May 8, 2025 - In Java 8, the Time API introduced two new classes: Duration and Period. If we want to calculate the difference between two date-times in a time-based (hour, minutes, or seconds) amount of time, we can use the Duration class:
🌐
Medium
medium.com › @AlexanderObregon › javas-period-between-method-explained-c32f4cd996c6
Java’s Period.between() Method Explained | Medium
January 1, 2025 - Difference: 2 years, 6 months, 16 days. ... The method calculates the gap between 2022-06-01 and 2024-12-17, breaking it into years, months, and days. This is useful when comparing two fixed dates or measuring durations between past events.
Top answer
1 of 12
129
import java.util.Calendar;
import java.util.Locale;
import static java.util.Calendar.*;
import java.util.Date;

public static int getDiffYears(Date first, Date last) {
    Calendar a = getCalendar(first);
    Calendar b = getCalendar(last);
    int diff = b.get(YEAR) - a.get(YEAR);
    if (a.get(MONTH) > b.get(MONTH) || 
        (a.get(MONTH) == b.get(MONTH) && a.get(DATE) > b.get(DATE))) {
        diff--;
    }
    return diff;
}

public static Calendar getCalendar(Date date) {
    Calendar cal = Calendar.getInstance(Locale.US);
    cal.setTime(date);
    return cal;
}

Note: as Ole V.V. noticed, this won't work with dates before Christ due how Calendar works.

2 of 12
55

tl;dr

ChronoUnit.YEARS.between( 
    LocalDate.of( 2010 , 1 , 1 ) , 
    LocalDate.now( ZoneId.of( "America/Montreal" ) ) 
)

Test for zero years elapsed, and one year elapsed.

ChronoUnit.YEARS.between( 
    LocalDate.of( 2010 , 1 , 1 )  , 
    LocalDate.of( 2010 , 6 , 1 ) 
)

0

ChronoUnit.YEARS.between( 
    LocalDate.of( 2010 , 1 , 1 )  , 
    LocalDate.of( 2011 , 1 , 1 ) 
)

1

See this code run at Ideone.com.

java.time

The old date-time classes really are bad, so bad that both Sun & Oracle agreed to supplant them with the java.time classes. If you do any significant work at all with date-time values, adding a library to your project is worthwhile. The Joda-Time library was highly successful and recommended, but is now in maintenance mode. The team advises migration to the java.time classes.

Much of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport and further adapted to Android in ThreeTenABP (see How to use…).

LocalDate start = LocalDate.of( 2010 , 1 , 1 ) ;
LocalDate stop = LocalDate.now( ZoneId.of( "America/Montreal" ) );
long years = java.time.temporal.ChronoUnit.YEARS.between( start , stop );

Dump to console.

System.out.println( "start: " + start + " | stop: " + stop + " | years: " + years ) ;

start: 2010-01-01 | stop: 2016-09-06 | years: 6



About java.time

The java.time framework is built into Java 8 and later. These classes supplant the troublesome old legacy date-time classes such as java.util.Date, Calendar, & SimpleDateFormat.

The Joda-Time project, now in maintenance mode, advises migration to the java.time classes.

To learn more, see the Oracle Tutorial. And search Stack Overflow for many examples and explanations. Specification is JSR 310.

You may exchange java.time objects directly with your database. Use a JDBC driver compliant with JDBC 4.2 or later. No need for strings, no need for java.sql.* classes.

Where to obtain the java.time classes?

  • Java SE 8, Java SE 9, Java SE 10, Java SE 11, and later - Part of the standard Java API with a bundled implementation.
  • Java 9 adds some minor features and fixes.
  • Java SE 6 and Java SE 7
  • Most of the java.time functionality is back-ported to Java 6 & 7 in ThreeTen-Backport.
  • Android
  • Later versions of Android bundle implementations of the java.time classes.
  • For earlier Android (<26), the ThreeTenABP project adapts ThreeTen-Backport (mentioned above). See How to use ThreeTenABP….

🌐
GeeksforGeeks
geeksforgeeks.org › dsa › find-the-duration-of-difference-between-two-dates-in-java
Find the duration of difference between two dates in Java - GeeksforGeeks
July 15, 2025 - Given two dates start_date and end_date with time in the form of strings, the task is to find the difference between two dates in Java. Examples: Input: start_date = "10-01-2018 01:10:20", end_date = "10-06-2020 06:30:50" Output: 2 years, 152 days, 5 hours, 20 minutes, 30 seconds Input: start_date = "10-01-2019 01:00:00", end_date = "10-06-2020 06:00:00" Output: 1 years, 152 days, 5 hours, 0 minutes, 0 seconds
🌐
How to do in Java
howtodoinjava.com › home › java date time › java – difference between two dates
Java - Difference Between Two Dates - HowToDoInJava
February 18, 2022 - LocalDate endofCentury = LocalDate.of(2014, 01, 01); LocalDate now = LocalDate.now(); Period diff = Period.between(endofCentury, now); System.out.printf("Difference is %d years, %d months and %d days old", diff.getYears(), diff.getMonths(), diff.getDays()); Duration represents time difference in a smaller time-based amount of time such as hours, minutes, seconds, nanoseconds etc. LocalDateTime dateTime = LocalDateTime.of(1988, 7, 4, 0, 0); LocalDateTime dateTime2 = LocalDateTime.now(); int diffInNano = java.time.Duration.between(dateTime, dateTime2).getNano(); long diffInSeconds = java.time.Duration.between(dateTime, dateTime2).getSeconds(); long diffInMilli = java.time.Duration.between(dateTime, dateTime2).toMillis(); long diffInMinutes = java.time.Duration.between(dateTime, dateTime2).toMinutes(); long diffInHours = java.time.Duration.between(dateTime, dateTime2).toHours();
🌐
w3resource
w3resource.com › java-exercises › datetime › java-datetime-exercise-30.php
Java - Difference between two dates (year, months, days)
Write a Java program to compute and display the precise period between two dates using the Period class. Write a Java program to compare two dates and output the difference in a "Y years, M months, D days" format.
🌐
Medium
medium.com › @AlexanderObregon › calculating-the-difference-between-two-dates-in-java-fcd6ebb28994
Calculating the Difference Between Two Dates in Java
September 13, 2025 - A call with YEARS will return only the whole years between the two dates, ignoring partial years. ChronoUnit also supports much larger scales, making it useful for historical data.
🌐
Level Up Lunch
leveluplunch.com › java › examples › number-of-years-between-two-dates
Years between two dates - Java
February 7, 2014 - This example will demonstrate how to find the number of years between two dates using Java 8 date time api and Joda time. We will set the start date to December 25, 2004 and the end date to January 1, 2006. Then we will find the number of years between the start date and end date which equates to 1 year. This snippet will find the difference between two dates in years using java 8 Duration.between and ChronoUnit.YEARS.
Find elsewhere
🌐
Blogger
javarevisited.blogspot.com › 2016 › 10 › how-to-get-number-of-months-and-years-between-two-dates-in-java.html
3 ways to get number of months and year between two dates in Java? Examples
* * @author WINDOWS 8 */ public class Java8Demo { public static void main(String args[]) { // Using Calendar - calculating number of months between two dates Calendar birthDay = new GregorianCalendar(1955, Calendar.MAY, 19); Calendar today = new GregorianCalendar(); today.setTime(new Date()); int yearsInBetween = today.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR); int monthsDiff = today.get(Calendar.MONTH) - birthDay.get(Calendar.MONTH); long ageInMonths = yearsInBetween*12 + monthsDiff; long age = yearsInBetween; System.out.println("Number of months since James gosling born : " + ageInMon
🌐
Pega
support.pega.com › question › difference-between-two-dates
Difference Between the Two Dates | Support Center
February 2, 2024 - java.text.SimpleDateFormat format = new java.text.SimpleDateFormat("yyyyMMdd"); Date d1 = null; Date d2 = null; String difference = ""; try { java.time.LocalDate sDate = java.time.LocalDate.parse(startDate,java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")); java.time.LocalDate eDate = java.time.LocalDate.parse(endDate,java.time.format.DateTimeFormatter.ofPattern("yyyyMMdd")); java.time.Period period = java.time.Period.between(sDate,eDate); int years = period.getYears(); int months = period.getMonths(); int days = period.getDays(); return + years + " years, " + months + " months, and " + days + " days."; } catch (Exception e) { e.printStackTrace(); } return difference;
🌐
Java67
java67.com › 2020 › 01 › how-to-find-difference-between-two-dates-in-java8.html
How to find difference between two dates in Java 8? Example Tutorial | Java67
1) You can calculate the difference between dates by subtracting milliseconds because of java.util.Date always represents a date as milliseconds from 1st January UTC, but you need to address several dates time-related issues like leap seconds, ...
🌐
Javatpoint
javatpoint.com › how-to-calculate-date-difference-in-java
How to Calculate Date Difference in Java - Javatpoint
How to Calculate Date Difference in Java with java tutorial, features, history, variables, object, programs, operators, oops concept, array, string, map, math, methods, examples etc.
🌐
LabEx
labex.io › tutorials › java-how-to-calculate-date-difference-in-java-417749
How to calculate date difference in Java | LabEx
Sometimes, you may need to calculate the difference in years, months, and days between two dates. The Period class from the java.time package can help with this.
🌐
Netjstech
netjstech.com › 2017 › 11 › difference-between-two-dates-java-program.html
Difference Between Two Dates in Java | Tech Tutorials
August 24, 2022 - Java 8 onward you can use new date and time API classes Period and Duration to find difference between two dates. Period class is used to model amount of time in terms of years, months and days.
🌐
w3resource
w3resource.com › java-exercises › datetime › java-datetime-exercise-19.php
Java - Get year and months between two dates
3 weeks ago - Write a Java program to determine the number of complete months between two user-provided dates. Write a Java program to compute the gap in years and remaining months between two dates.
🌐
LearnJava
learnjava.co.in › how-to-find-the-number-of-years-between-two-dates
How to find the number of years between two Dates - LearnJava
December 27, 2021 - public static void main(String[] ... represent a Date. So in this code, both the input Dates are held within LocalDate objects. There is a method called until on the LocalDate class. This returns a Period instance....
Top answer
1 of 4
21

First you need to determine which one is older than the other. Then make use of a while loop wherein you test if the older one isn't after() the newer one. Invoke Calendar#add() with one (1) Calendar.YEAR on the older one to add the years. Keep a counter to count the years.

Kickoff example:

Calendar myBirthDate = Calendar.getInstance();
myBirthDate.clear();
myBirthDate.set(1978, 3 - 1, 26);
Calendar now = Calendar.getInstance();
Calendar clone = (Calendar) myBirthDate.clone(); // Otherwise changes are been reflected.
int years = -1;
while (!clone.after(now)) {
    clone.add(Calendar.YEAR, 1);
    years++;
}
System.out.println(years); // 32

That said, the Date and Calendar API's in Java SE are actually epic failures. There's a new Date API in planning for upcoming Java 8, the JSR-310 which is much similar to Joda-Time. As far now you may want to consider Joda-Time since it really eases Date/Time calculations/modifications like this. Here's an example using Joda-Time:

DateTime myBirthDate = new DateTime(1978, 3, 26, 0, 0, 0, 0);
DateTime now = new DateTime();
Period period = new Period(myBirthDate, now);
int years = period.getYears();
System.out.println(years); // 32

Much more clear and concise, isn't it?

2 of 4
10
Calendar dobDate; // Set this to date to check
Calendar today = Calendar.getInstance();
int curYear = today.get(Calendar.YEAR);
int curMonth = today.get(Calendar.MONTH);
int curDay = today.get(Calendar.DAY_OF_MONTH);

int year = dobDate.get(Calendar.YEAR);
int month = dobDate.get(Calendar.MONTH);
int day = dobDate.get(Calendar.DAY_OF_MONTH);

int age = curYear - year;
if (curMonth < month || (month == curMonth && curDay < day)) {
    age--;
}

This avoids looping and should be accurate to the day.