Java 8 Examplesjava-date-handling-examplesJava8

How to find the number of years between two Dates

Posted On
Posted By admin

Prior to Java 8, you had to write complex logic to find the number of years between two dates. The DateTime API introduced from Java 8 onwards provides some methods that let you easily find the number of years between two dates.

The following code demonstrates this:

public static void main(String[] args) {
  LocalDate date1 = LocalDate.parse("1997-04-28");
  LocalDate date2 = LocalDate.parse("2015-11-25");
  Period period = date1.until(date2);
  int yearsBetween = period.getYears();
  System.out.println("yearsBetween:"+yearsBetween);
}

Java 8 has added a LocalDate class to 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. Period has a method called getYears which returns the number of years. So this code prints the following output:

yearsBetween:18
If you'd like to watch a detailed video tutorial of this topic or other related topics, do check out my new course Learn Java 8 New Features

If you like this post, please do let me know via the comments box below.  You can also connect with me via my Facebook Page or subscribe to my Youtube channel!

Related Post

One thought on “How to find the number of years between two Dates
  1. Kai

    Great article! Thank you 🙂 http://gdl.referata.com/wiki/User:AlphonsoCullen1

leave a Comment