Java program to calculate Age from Date of birth

Java program to calculate Age from Date of birth The following Java program is to calculate age from date of birth. The age can be calculated using different ways.

Method 1: Direct age calculation

Using the package java.time.LocalDate the age is calculated when the dob is known. using LocalDate.now() the current date is obtained. using the method between() in java.time.Period the current date and dob are compared. The final age can be obtained using diff.getYears(), diff.getMonths() and diff.getDays() methods.

Syntax: Period diff=Period.between(l, now);

Method 2: Using Calendar object

Using Calendar object we can also calculate age when dob is in String format. Convert the String to Date object and use getInstance() and setTime() methods to assign date to calendar objects. using the below code the year, month and date are obtained separately.

Syntax:

int year=c.get(Calendar.YEAR);

int month=c.get(Calendar.MONTH)+1;

int date=c.get(Calendar.DATE);

Using between() method in java.time.Period package the year, month and date obtained from calendar object is compared to current date obtained by LocalDate.now() method.We can get the age using diff.getYears() method.

Dobconversion.java

package com.candidjava.time;

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 DobConversion 
{
public static void main(String[] args) throws ParseException 
{
	//direct age calculation 
	LocalDate l=LocalDate.of(1998, 04, 23); //specify year, month, date directly
	LocalDate now=LocalDate.now(); 		//gets localDate
	Period diff=Period.between(l, now);	//difference between the dates is calculated
	System.out.println(diff.getYears() +"years" +diff.getMonths() +"months" +diff.getDays() +"days");

	//using Calendar Object
	String s="1994/06/23";
	SimpleDateFormat sdf=new SimpleDateFormat("yyyy/MM/dd");
	Date d=sdf.parse(s);
	Calendar c=Calendar.getInstance();
	c.setTime(d);
	 int year=c.get(Calendar.YEAR);
	 int month=c.get(Calendar.MONTH)+1;
	 int date=c.get(Calendar.DATE);
	LocalDate l1 = LocalDate.of(year, month, date);
	LocalDate now1 = LocalDate.now();
	Period diff1 = Period.between(l1, now1);
	System.out.println("age:" +diff1.getYears() +"years");
}
}

Output:

20years8months15days
age:24years

Leave a Reply

Your email address will not be published. Required fields are marked *