how to calculate age in java code example
Example 1: java age from date
LocalDate today = LocalDate.now();
LocalDate birthday = LocalDate.of(1987, 09, 24);
Period period = Period.between(birthday, today);
System.out.println(period.getDays());
System.out.println(period.getMonths());
System.out.println(period.getYears());
Example 2: how to calculate age from date of birth in java using calendar
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 {
LocalDate l = LocalDate.of(1998, 04, 23);
LocalDate now = LocalDate.now();
Period diff = Period.between(l, now);
System.out.println(diff.getYears() + "years" + diff.getMonths() + "months" + diff.getDays() + "days");
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");
}
}
Example 3: how to calculate age on entry of dob in java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Calendar;
import java.util.Date;
public class AgeCalculator
{
private static Age calculateAge(Date birthDate)
{
int years = 0;
int months = 0;
int days = 0;
Calendar birthDay = Calendar.getInstance();
birthDay.setTimeInMillis(birthDate.getTime());
long currentTime = System.currentTimeMillis();
Calendar now = Calendar.getInstance();
now.setTimeInMillis(currentTime);
years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
int currMonth = now.get(Calendar.MONTH) + 1;
int birthMonth = birthDay.get(Calendar.MONTH) + 1;
months = currMonth - birthMonth;
if (months < 0)
{
years--;
months = 12 - birthMonth + currMonth;
if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
months--;
} else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
{
years--;
months = 11;
}
if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
{
int today = now.get(Calendar.DAY_OF_MONTH);
now.add(Calendar.MONTH, -1);
days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
}
else
{
days = 0;
if (months == 12)
{
years++;
months = 0;
}
}
return new Age(days, months, years);
}
public static void main(String[] args) throws ParseException
{
SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
Date birthDate = sdf.parse("29/11/1981");
Age age = calculateAge(birthDate);
System.out.println(age);
}
}