Calculating the age is a common requirement in many applications as it is used for age verification and for providing personalized experiences. In this article, we will see how to calculate a person’s age using their date of birth in Java.
Get the date of birth from the user
To calculate the date of birth, first, we need to get the person’s date of birth. We can this as input from the user or retrieve it from the database. We will use the java.time.LocalDate
class to represent the date of birth.
Calculate the age
Using the java.time.Period
class, we can easily calculate the age.
First, we create a Period object by calling the between()
method by passing the date of birth and the current date as an argument. This will give us the duration between the two dates in years, months, and days.
Retrieve the age
Using the Period
object, we can retrieve the age in years using the getYears()
method. This will give us the person’s age based on the date of birth.
Following is the example:
import java.time.LocalDate;
import java.time.Period;
public class AgeCalculator {
public static void main(String[] args) {
// Obtain the date of birth
LocalDate dateOfBirth = LocalDate.of(1990, 5, 15);
// Calculate the age
LocalDate currentDate = LocalDate.now();
Period period = Period.between(dateOfBirth, currentDate);
int age = period.getYears();
// Print the age
System.out.println("Age: " + age);
}
}
FAQs:
Q: Can I calculate the age accurately if the date of birth includes the time?
A: When calculating age, only the date portion is considered, not the time. Therefore, the time component in the date of birth can be ignored for age calculation.
Q: Is there a way to calculate age in months or days as well?
A: Yes, the Period class provides methods like getMonths() and getDays(), which allow you to retrieve the age in months and days, respectively. Modify the code as per your specific requirements to calculate age in different units.
References:
https://docs.oracle.com/javase/8/docs/api/java/time/package-summary.html