w3resource

Java: 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.

Flowchart:

Flowchart: Java DateTime, Calendar Exercises - Calculate your age

Alternate Soluation:

Java Code:

//MIT License: https://bit.ly/35gZLa3
import java.time.LocalDate;
import java.time.Period;
import java.time.temporal.ChronoUnit;
import java.util.Calendar;
import java.util.Date;

public class Main {

    public static void main(String[] args) {

        LocalDate start_Local_date = LocalDate.of(1985, 06, 4);
        LocalDate end_Local_date = LocalDate.now();

        long years = ChronoUnit.YEARS.between(start_Local_date, end_Local_date);
        System.out.println("Age in years: "+years + "y ");

        Period period_Between = Period.between(start_Local_date, end_Local_date);
        System.out.println("Age in years/months/dates: "+period_Between.getYears() + "y "
                + period_Between.getMonths() + "m "
                + period_Between.getDays() + "d");
    }
}

Sample Output:

Age in years: 34y 
Age in years/months/dates: 34y 5m 12d

Flowchart:

Flowchart: Java DateTime, Calendar Exercises - Define and extract zone offsets.

Java Code Editor:

Improve this sample solution and post your code through Disqus

Previous: Write a Java program to compute the difference between two dates (Hours, minutes, milli, seconds and nano).
Next: Write a Java program to get the next and previous Friday.

What is the difficulty level of this exercise?

Test your Programming skills with w3resource's quiz.



Follow us on Facebook and Twitter for latest update.