Write a Java program to calculate your age


This Java program calculates a person's age based on their date of birth. Here are the explanations of the code:

  • import java.time.*; - imports the Java time library.
  • class Calculate_Age - defines a new class called Calculate_Age.
  • public static void main(String[] args) - the main method of the class, which is the starting point of the program.
  • LocalDate pdt = LocalDate.of(1992,03,9); - creates a new LocalDate object called pdt that represents the person's date of birth.
  • LocalDate tdt = LocalDate.now(); - creates a new LocalDate object called tdt that represents the current date.
  • Period diff = Period.between(pdt, tdt); - calculates the difference between the two dates, and stores the result in a Period object called diff.
  • System.out.println("Date of Birth : "+pdt); - prints the date of birth.
  • System.out.println("Age : "+diff.getYears()); - prints the person's age in years, which is obtained from the diff object using the getYears() method.
  • System.out.println("Years : "+diff.getYears()); - prints the number of years in the difference.
  • System.out.println("Months : "+diff.getMonths()); - prints the number of months in the difference.
  • System.out.println("Days : "+diff.getDays()); - prints the number of days in the difference.

Source Code

import java.time.*;
class Calculate_Age
{  
	public static void main(String[] args)
	{
		LocalDate pdt = LocalDate.of(1992,03,9);
		LocalDate tdt = LocalDate.now();
		Period diff = Period.between(pdt, tdt);
		System.out.println("Date of Birth : "+pdt);
		System.out.println("Age : "+diff.getYears());
		System.out.println("Years : "+diff.getYears());
		System.out.println("Months : "+diff.getMonths());
		System.out.println("Days : "+diff.getDays());
	}
}

Output

Date of Birth : 1992-03-09
Age : 30
Years : 30
Months : 7
Days : 27

Example Programs