Java 8 Program to Find the Age of a Person if the Birthday Date has Given

1. Introduction

Determining the age of a person given their birthday is a common programming task that demonstrates handling dates and calculating differences between them. In this blog post, we will use Java 8's new Date and Time API to calculate a person's age based on their birthday. Java 8 introduced the java.time package, providing a comprehensive model for date and time operations.

2. Program Steps

1. Import the necessary classes from the java.time package.

2. Read the birthday date from the user.

3. Use the LocalDate class to represent the birthday and the current date.

4. Calculate the period between the current date and the birthday.

5. Extract the years from the period, which represents the person's age.

6. Display the calculated age.

3. Code Program

import java.time.LocalDate;
import java.time.Period;
import java.util.Scanner;

public class CalculateAge {
    public static void main(String[] args) {
        // Creating a Scanner object for reading input
        Scanner scanner = new Scanner(System.in);
        System.out.println("Enter your birthdate (YYYY-MM-DD):");
        String birthDateString = scanner.nextLine();
        scanner.close(); // Closing the scanner

        // Parsing the input string to a LocalDate
        LocalDate birthDate = LocalDate.parse(birthDateString);

        // Getting the current date
        LocalDate currentDate = LocalDate.now();

        // Calculating the period between the birthdate and the current date
        Period age = Period.between(birthDate, currentDate);

        // Displaying the age
        System.out.println("You are " + age.getYears() + " years old.");
    }
}

Output:

Enter your birthdate (YYYY-MM-DD):
2000-01-01
You are 23 years old.

Explanation:

1. The program starts by importing classes from the java.time package, which are used for handling dates in Java 8.

2. A Scanner object is created to read the user's birthdate, which is expected to be in the format YYYY-MM-DD.

3. The user's input is then parsed into a LocalDate object representing the birthdate. LocalDate is an immutable date-time object that represents a date, often viewed as year-month-day.

4. The current date is obtained using LocalDate.now(), and the Period class is used to calculate the period between the current date and the birthdate. The Period class models a quantity or amount of time in terms of years, months, and days.

5. The years part of the age is then extracted using the getYears() method on the Period object, representing the person's age.

6. Finally, the calculated age is displayed to the user.

7. The Scanner object is closed to prevent resource leaks, adhering to best practices in handling user input.

Comments