Calculate age from date of birth in Java

1. Introduction

Calculating age from a date of birth is a common requirement in many applications, such as form validations, eligibility checks, and record management. Java provides multiple ways to calculate the age, both before and after Java 8, utilizing classes like Calendar and LocalDate.

Key Points

1. Before Java 8, the Calendar class is typically used to calculate differences between dates.

2. Starting with Java 8, the LocalDate and Period classes provide a more modern and efficient approach to handling dates and calculating differences.

3. The ChronoUnit class can precisely measure time in terms of years, months, and days.

2. Program Steps

1. Import necessary classes.

2. Set up dates using both pre-Java 8 and post-Java 8 methods.

3. Calculate age using Calendar and LocalDate.

4. Display the results.

3. Code Program

import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static void main(String[] args) {

        System.out.println("Before JDK 8:");
        Calendar startDate = Calendar.getInstance();
        startDate.set(1991, 06, 1);
        Calendar endDate = Calendar.getInstance();
        endDate.setTime(new Date());

        int yearsc = endDate.get(Calendar.YEAR) - startDate.get(Calendar.YEAR);

        if (yearsc > 0) {
            if (startDate.get(Calendar.MONTH) > endDate.get(Calendar.MONTH)
                    || (startDate.get(Calendar.MONTH) == endDate.get(Calendar.MONTH)
                    && startDate.get(Calendar.DAY_OF_MONTH) > endDate.get(Calendar.DAY_OF_MONTH))) {
                yearsc--;
            }
        }

        System.out.println(yearsc + "y");
        System.out.println("\nStarting with JDK 8");
        LocalDate startLocalDate = LocalDate.of(1991, 06, 1);
        LocalDate endLocalDate = LocalDate.now();

        long years = ChronoUnit.YEARS.between(startLocalDate, endLocalDate);
        System.out.println(years + "y ");

        Period periodBetween = Period.between(startLocalDate, endLocalDate);
        System.out.println(periodBetween.getYears() + "y "
                + periodBetween.getMonths() + "m "
                + periodBetween.getDays() + "d");
    }
}

Output:

Before JDK 8:
30y
Starting with JDK 8
30y
30y 5m 9d

Explanation:

1. Before JDK 8: The Calendar class is used to set a start date and compare it with the current date. The years are calculated by subtracting the start year from the current year. Adjustments are made if the current date is before the birthday in the current year to correct the age.

2. Starting with JDK 8: LocalDate provides a cleaner way to represent dates without time. ChronoUnit.YEARS.between() gives a quick way to calculate the difference in years. Additionally, Period.between() is used to get the exact difference in years, months, and days.

3. Output Explanation: The program prints the calculated years using both methods. The pre-Java 8 method outputs only the years, while the Java 8 method provides more detailed information, showing years, months, and days.

4. Utility and Flexibility: This example shows two methods to achieve the same result, offering flexibility depending on the Java version and specific needs for precision in the application.


Comments