1LocalDate today = LocalDate.now();
2LocalDate birthday = LocalDate.of(1987, 09, 24);
3
4Period period = Period.between(birthday, today);
5
6//Now access the values as below
7System.out.println(period.getDays());
8System.out.println(period.getMonths());
9System.out.println(period.getYears());
1import java.text.ParseException;
2import java.text.SimpleDateFormat;
3import java.util.Calendar;
4import java.util.Date;
5
6public class AgeCalculator
7{
8 private static Age calculateAge(Date birthDate)
9 {
10 int years = 0;
11 int months = 0;
12 int days = 0;
13
14 //create calendar object for birth day
15 Calendar birthDay = Calendar.getInstance();
16 birthDay.setTimeInMillis(birthDate.getTime());
17
18 //create calendar object for current day
19 long currentTime = System.currentTimeMillis();
20 Calendar now = Calendar.getInstance();
21 now.setTimeInMillis(currentTime);
22
23 //Get difference between years
24 years = now.get(Calendar.YEAR) - birthDay.get(Calendar.YEAR);
25 int currMonth = now.get(Calendar.MONTH) + 1;
26 int birthMonth = birthDay.get(Calendar.MONTH) + 1;
27
28 //Get difference between months
29 months = currMonth - birthMonth;
30
31 //if month difference is in negative then reduce years by one
32 //and calculate the number of months.
33 if (months < 0)
34 {
35 years--;
36 months = 12 - birthMonth + currMonth;
37 if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
38 months--;
39 } else if (months == 0 && now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
40 {
41 years--;
42 months = 11;
43 }
44
45 //Calculate the days
46 if (now.get(Calendar.DATE) > birthDay.get(Calendar.DATE))
47 days = now.get(Calendar.DATE) - birthDay.get(Calendar.DATE);
48 else if (now.get(Calendar.DATE) < birthDay.get(Calendar.DATE))
49 {
50 int today = now.get(Calendar.DAY_OF_MONTH);
51 now.add(Calendar.MONTH, -1);
52 days = now.getActualMaximum(Calendar.DAY_OF_MONTH) - birthDay.get(Calendar.DAY_OF_MONTH) + today;
53 }
54 else
55 {
56 days = 0;
57 if (months == 12)
58 {
59 years++;
60 months = 0;
61 }
62 }
63 //Create new Age object
64 return new Age(days, months, years);
65 }
66
67 public static void main(String[] args) throws ParseException
68 {
69 SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
70 Date birthDate = sdf.parse("29/11/1981");
71 Age age = calculateAge(birthDate);
72 System.out.println(age);
73 }
74}
75