Java Program That Calculates the Age of a Person

In this post, we will write a Java program that calculates the age of a person.
Check out Java 8 examples at Java 8 Examples
Checkout all Java programs at 100+ Java Programs 

Java Program That Calculates the Age of a Person

package net.sourcecodeexamples.java;

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(1990, 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(1990, 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 2m 10d
Check out Java 8 examples at Java 8 Examples
Checkout all Java programs at 100+ Java Programs 

Comments