Learn how to calculate age from a birthdate in Java 8 using the Date and Time API. The combination of LocalDate and ChronoUnit.YEARS.between() provides a clean, accurate, and efficient way to determine a person’s age from their birthdate.
Code Explanation (Step-by-Step)
- LocalDate.now() gets the current system date.
- LocalDate.of(year, month, day) creates the birth date object.
- ChronoUnit.YEARS.between() calculates the total number of years between the birth date and the current date.
- Print the calculated age.
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.
Calculate Age from a Birthdate in Java 8 Using Period
import java.time.LocalDate;
import java.time.Period;
public class CalculateAge {
public static void main(String[] args) {
LocalDate dateOfBirth = LocalDate.of(1984, 7, 8);
LocalDate currentDate = LocalDate.now();
int age = Period.between(dateOfBirth, currentDate).getYears();
System.out.println("Your age is " + age + " years old.");
}
}
FAQ
How do you calculate age in Java 8?
Use LocalDate and ChronoUnit.YEARS.between() to calculate the difference between a birth date and the current date.
What is LocalDate in Java 8?
LocalDate is a class in the Java 8 Date and Time API that represents a date without time and timezone information.
Why use ChronoUnit.YEARS?
ChronoUnit.YEARS calculates the number of complete years between two dates accurately.
Can I calculate age from user input in Java 8?
Yes, you can accept a birthdate from the user and use LocalDate along with ChronoUnit.YEARS.between() to calculate age.
Which package contains LocalDate?
LocalDate belongs to the java.time package introduced in Java 8.
What is use of LocalDate.now()?
LocalDate.now() gets the current system date.
What use of Period.between()?
Period.between(dateOfBirth, currentDate) calculates the difference between the two dates.