Date and Time

How to calculate age from date of birth in java

public final class Period extends Object

A date-based amount of time in the ISO-8601 calendar system, such as ‘2 years, 3 months and 4 days’. This class models a quantity or amount of time in terms of years, months and days. See Duration for the time-based equivalent to this class. Durations and periods differ in their treatment of daylight savings time when added to ZonedDateTime. A Duration will add an exact number of seconds, thus a duration of one day is always exactly 24 hours. By contrast, a Period will add a conceptual day, trying to maintain the local time.

public int getDays()

Gets the amount of days of this period. This returns the days unit.

public int getMonths()

Gets the amount of months of this period. This returns the months unit.

public int getYears()

Gets the amount of years of this period. This returns the years unit.

package com.candidjava.datetime;

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.Period;
import java.util.Calendar;
import java.util.Date;

public class AgeCalculation {
	public static void main(String[] args) throws ParseException {
		//Using Period Class
		LocalDate bday = LocalDate.of(1995, 8, 27);
		LocalDate today = LocalDate.now();
		Period age = Period.between(bday, today);
		int years = age.getYears();
		int months = age.getMonths();
		int days = age.getDays();
		System.out.println("Age:" + years + " Years " + months + " Months " + days + " days ");
		System.out.println("--------------------------------------------");
		//Using Calendar Class
		String date="27-08-1995";
		SimpleDateFormat dateFormat=new SimpleDateFormat("dd-MM-yyyy");
		Date convertedDate=dateFormat.parse(date);
		Calendar calendar=Calendar.getInstance();
		calendar.setTime(convertedDate);
		int year=calendar.get(Calendar.YEAR);
		int month=calendar.get(Calendar.MONTH)+1;
		int day=calendar.get(Calendar.DATE);
		LocalDate l1=LocalDate.of(year, month, day);
		LocalDate l2=LocalDate.now();
		Period myage=Period.between(l1,l2);
		System.out.println("Age:"+myage.getYears()+" Years "+myage.getMonths()+" Months "+myage.getDays()+" Days" );
		
	}

}

OUTPUT

Age:25 Years 2 Months 22 days 
--------------------------------------------
Age:25 Years 2 Months 22 Days