How do I calculate someone’s age in Java 8?

Here we are calculate someone’s age from a birthdate using the Data/Time API in Java 8.

  • User LocalDate.now() method to get the current date.
  • Create the LocalDate instance named dob, and it can take the dob in the format of year, month, and day.

Syntax:- LocalDate localDate = LocalDate.of(year, month, dayOfMonth);

  • Here ChronoUnit.YEARS is used to calculate the difference in years between dateOfBirth and currentDate objects.
import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

public class CalculateAge {
	public static void main(String[] args) {

		LocalDate currentDate = LocalDate.now();
		LocalDate dateOfBirth = LocalDate.of(1984, 7, 8);
		long totalYears = ChronoUnit.YEARS.between(dateOfBirth, currentDate);
		System.out.println("your age is " + totalYears + " year old.");
	}
}

Output :-
your age is 40 year old.