w3resource logo


Java Programming Exercies

Java DateTime, Calendar Exercises: Calculate your age

Secondary Nav

Java DateTime, Calendar : Exercise-32 with Solution

Write a Java program to calculate your age.

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  27 years, 5 months and 8 days old. 

Java Practice online:

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());
   }
}



Join our Question Answer community to learn and share your programming knowledge.

Help the community:

Python: Fizzbuzz

C++: Decimal to binary conversion

JavaScript: Need Help in JavaScript

Python: Help me with this program