w3resource logo


Java Programming Exercies

Java DateTime, Calendar Exercises: Calculate your age

Java DateTime, Calendar : Exercise-32 with Solution

Write a Java program to calculate your age.

Sample Solution:

Java Code:

import java.time.*;
import java.util.*;

public class Exercise32 {  
   public static void main(String[] args)
        // date of birth
        LocalDate pdate = LocalDate.of(1989, 04, 11);
        // current date
        LocalDate now = LocalDate.now();
        // difference between current date and date of birth
        Period diff = Period.between(pdate, now);
     System.out.printf("\nI am  %d years, %d months and %d days old.\n\n", 
                    diff.getYears(), diff.getMonths(), diff.getDays());

Sample Output:

I am  28 years, 2 months and 10 days old.

N.B.: The result may varry for your system date and time.

Java Code Editor:

Improve this sample solution and post your code through Disqus