×

Java calculate age

In this section, we will create a Java program that calculates age from the given date of birth or current date.

In order to get the date of birth from the current date or any specific date, we should follow the steps given below.

  • The user can read the date of birth or enter (DOB).
  • Transform the DOB to LocalDate objects.
  • Using the now() function, you may get the current date (as a LocalDate object).
  • By using between() function, find the period (difference) between both two dates (DOB and current date).

Ways to Calculate Age

  • By using the Period Class
  • By using the Enum ChronoUnit
  • By using the calendar class
  • By using the Joda Library

By Making Use of the Period Class

Java 8 includes the Period class, which is part of java.time package. It is an unchangeable class representing a period in the years, months, and days. The class has several static methods for manipulating dates. The Period class includes the between() method that determines age.

Syntax:

public static Period between(LocalDate birthDateInclusive, LocalDate currentDateExclusive) 

The method takes two parameters: the beginning and ending dates of the LocalDate type. It displays the period between two dates (the date of birth and the current date). The opening date is provided, but the finish date is not. It could also represent a negative period if the end date is earlier than the start time.

Example: AgeCalculateEx1.java

//this program is for finding the age based on the date of birth
//by using the periodic class
//import section
import java.time.LocalDate;  
import java.time.Period;  
import java.util.Scanner;  
public class AgeCalculateEx1  
{  
public static void main(String args[])   
{  
System.out.print("Enter your birthday in the form of YYYY-MM-DD .: ");  
Scanner sc = new Scanner(System.in);  
//the input string will read the data from the user 
String in = sc.nextLine();  
sc.close();  
//The parse() function extracts a LocalDate object from one text string, such as 1999-4-9  
LocalDate dateofbirth = LocalDate.parse(in);  
// the print statement will display the age of the person  
System.out.println("Your's age is: " + calculateAge(dateofbirth));  
}  
// the method ageCalculate. will calculate the age of the 
//person based on the date of birth
public static int calculateAge(LocalDate dateofbirth)   
{  
//making an instance for the LocalDate class as well as running the now() method
//the now() function retrieves the timestamp from the input signal in the default timeline
LocalDate currentDate = LocalDate.now();  
//computes the time elapsed between two different dates, then returns the years
if ((dateofbirth != null) && (currentDate != null))   
{  
return Period.between(dateofbirth, currentDate).getYears();  
}  
else  
{  
return 0;  
}  
}  
}

Output:

Enter your birthday in the form of YYYY-MM-DD .: 2000-05-19
Your's age is: 22

The below program will describe the age with months and days.

Example: CalculateAgeEx2.java

// this program is for calculating the age
// importing the required packages
import java.time.*;  
import java.util.*;  
public class CalculateAgeEx2  
{    
public static void main(String args[])  
{  
//gets a LocalDate object based on the year, month, and the date  
LocalDate dateofbirth = LocalDate.of(1988, 12, 13);  
// the current timestamp is obtained from the system 
LocalDate currentDate = LocalDate.now();  
// the differences between the 2 dates are calculated  
Period time = Period.between(dateofbirth, currentDate);  
// the result of the differences between the months and years is then printed
System.out.printf(“You are %d years , %d months and %d days.", time.getYears(), time.getMonths(), time.getDays());  
}  
}  

Output

You are 33 years , 9 months and 25 days

By using the Enum ChronoUnit

ChronoUnit is an enumeration in Java that offers a consistent set of chronological interval units. It enables unit-based manipulation of date, time, or date-time-space. The ChronoUnit enumeration also has a between() function, similar to the between() function of the Java Period class. This also computes the period (in units) elapsed among different temporal items.

Syntax:

public long between(Temporal temp1Inclusive, Temporal temp2Exclusive) 

The algorithm takes two Temporal parameters, temporal1 and temporal2.

And utilized the of() function of the Java LocalDate class in the following application. The technique generates a LocalDate object from a year, month, and date. It generates a LocalDate that includes the year, month, and day of that month supplied. The of() function is a replacement again for LocalDate.now() function.

Example: AgeCalculatorEx3.java

// this program is for calculating the age
// importing the required packages
//the program works on Java 8 and later versions  
import java.time.LocalDate;  
import java.time.Period;  
import java.time.temporal.ChronoUnit;  
import java.util.Scanner;  
public class  AgeCalculatorEx3  
{  
public static void main(String args[])   
{  
LocalDate initialDate = LocalDate.of(1998, 01, 20);  
LocalDate lastDate = LocalDate.of(2022, 06, 02); 
// an alternate method for the local.now() method
// the function will calculate the time between the given period  
long year= ChronoUnit.YEARS.between(initialDate, lastDate);  
// the resulting age will be printed as the years  
System.out.println("Your age is: "+year);  
}  
}  

Output

Your age is: 24

By using the Calender class in Java

The java.util package contains an abstract class called Calendar. It offers techniques for transforming dates between a given point in time and a collection of calendar variables such as MONTH, YEAR, HOUR, etc. It is an Object-based class that performs Related acts.

The below program will implement the calender class for finding the age.

Example: AgeCalculatorEx4.java

// this program is for calculating the age
// importing the required packages
import java.util.Calendar;  
import java.util.GregorianCalendar;  
public class AgeCalculatorEx4   
{  
public static void main(String args[])   
{  
// A constructor was created for the class, and then it has the parameters as date of birth  
Calendar dateofbirth= new GregorianCalendar(1989, 10, 5);  
// the current date is added 
Calendar currDate = new GregorianCalendar();  
// the current date and also the birth year is calculated
int ag = currDate.get(Calendar.YEAR) - dateofbirth.get(Calendar.YEAR);  
if ((dateofbirth.get(Calendar.MONTH) > currDate.get(Calendar.MONTH)) || (dateofbirth.get(Calendar.MONTH) == currDate.get(Calendar.MONTH) && dateofbirth.get(Calendar.DAY_OF_MONTH) > currDate.get(Calendar.DAY_OF_MONTH)))   
{  
// the value of the age is then decreased to 1      
ag--;  
}  
// the result of age is printed
System.out.println(" The age of a person is: "+ag);  
}  
} 

Output

The age of a person is: 32

By using the Joda Library

Joda is now a third-party package that offers a collection of duration values (such as hour, minutes, days, month, year). Like other Java time and date classes, it is an immutable date-time class. A class has the feature of representing a time without the need for a time zone. It employs ISOChronology to express date and time.

In the following program, we generated two constructors for the LocalDate class (org.joda.time). The first LocalDate function Object(){ [native code] } accepts the birth date (dob), whereas the second LocalDate function Object() { [native code] } accepts the current date.

Syntax:

LocalDate(int year, int monthOfYear, int dayOfMonth) 

year: Accepts years in the format yyyy.

monthOfYear: A number around 1 and 12 is accepted.

dayOfMonth: A number between 1 and 31 is accepted.

YEARS is also another unchangeable class that we utilized. When dealing with a single year, we utilize this class. It denotes the number of years. The class offers the years between the () method for calculating the difference in years among two date objects. It takes two LocalDate instances as input.

The getYears() function is provided by the class to retrieve the years. It denotes the number of years in which this time comprises.

The below program will describe the implementation of the joda library.

Example: AgeCalculatorEx5.java

// this program is for calculating the age
// importing the required packages
//the program works on Java 8 and later versions  
import java.time.LocalDate;  
import java.time.Period;  
import java.time.temporal.ChronoUnit;  
import java.util.Scanner;  
public class  AgeCalculatorEx5  
{  
public static void main(String args[])   
{  
LocalDate initialDate = LocalDate.of(1999, 01, 20);  
LocalDate lastDate = LocalDate.of(2012, 06, 02); 
// an alternate method for the local.now() method
// the function will calculate the time between the given period  
long year= ChronoUnit.YEARS.between(initialDate, lastDate);  
// the resulting age will be printed as the years  
System.out.println("Your age is: "+year);  
}  
}  

Output

Your age is: 13

We may also make use of third-party libraries, including Date4J or Time4J.

The Date4J package is straightforward to use. However, it may not always produce the intended output, such as in the situation of leap year. As a result, calculating the date of the year is unreliable.

The Time4J package is a comprehensive high-end alternative for ancient Java classes like Date, Calendar, and SimpleDateFormat. It provides a complicated date, time, and period library in Java. It functions similarly to the Written in java approach. Replace LocalDate with PlainDates with ChronoUnit. YEARS besides CalendarUnit YEARS.


Related Topics

How to Convert char to String in Java

How to Convert char to String in Java There are two methods to convert char to String: Using String.valueOf(char) method Using Charcter.toString(char) method Using String.valueOf(char) method valueOf(char) is the static method of String class that...

2 minutes read.

How to Convert Integer to String in Java

How to Convert int to String in Java It is used when you want to convert an integer to String. You can convert int to String by using the following methods: Using...

3 minutes read.

Functional Interface in Java 8

A brief introduction to Interface in Java: Interfaces in Java are basically the blue print of classes. Before the appearance of Java 8, it was only possible to declare one or...

11 minutes read.

Self-Descriptive Numbers in Java

A number n is given. Identifying the self-descriptive numbers that exist between 1 and n is our task. Self-Descriptive Numbers The definition of a self-descriptive number, m, is a number with b...

6 minutes read.

Java String split() method

Java String split() method split current String against given regular expression and returns a char array. Syntax: public String split(String regex)                 public String split(String regex, int...

2 minutes read.

Int vs Integer in Java

In Java, numerical data can be stored using int or Integer. int and Integer both have different definitions but similar usage in Java. What is int in Java? int is a primitive...

4 minutes read.

Java array list remove time complexity

Java: We know that java is one of the programming languages. The main feature of java which is not in C or object oriented programming language is platform independence. Not only the...

7 minutes read.

How to Create Different Packages for Different Classes in Java

Packages in Java In Java, Packages are an assortment of classes, sub-packages, and connection points. i.e. A package addresses a word reference that contains a connected gathering of styles and points...

7 minutes read.

Difference Between Access Specifiers and Modifiers in Java

Java employs access modifiers to restrict a class's data members, member functions, and constructor. Access modifiers are essential when creating Java program and applications. Access modifiers in Java include: defaultpublicprotectedprivate Default Access Modifiers Without...

4 minutes read.

How to take String Input in Java

There are various ways to take String input in Java. In this section, we are going to discuss how to take String input in Java. There are following ways to...

5 minutes read.

How to Create an API in Java?

Introduction The API can be abbreviated as Application Programming Interface. An API is a combination of set of classes and interfaces. It is also equivalent to a simple java program. To...

12 minutes read.

All the important string methods in Java

What is a String? Strings are a bundle of different characters that are normally used in Java programming language. Strings are regarded as objects in the Java programming language. “String” is a...

4 minutes read.

Java ArraylistRemove() Time Complexity

In this tutorial, we will learn about how we can remove time complexity in Java ArrayList. But unless we will not learn what is ArrayList, we don’t understand this process....

7 minutes read.

Three Partition Problems in Java

In talks with leading IT organizations like Google, Amazon, TCS, Accenture, etc., this extremely intriguing subject is constantly brought up. The goal of the problem-solving exercise is to evaluate the...

8 minutes read.

Static class in Java

In Java, a class is a file containing the Java byte code. It can essentially specifically be executed on the JVM (Java Virtual Machine), fairly significant. The JVM is mostly...

7 minutes read.

Activity selection problem in Java

The activity selection problem is a multiple objective problem hat requires choosing non-conflicting tasks to complete within a specific amount of time from a list of tasks identified by a...

5 minutes read.

Permutation Coefficient in Java

In this tutorial, we will get familiar with the permutation coefficient in Java.  We will understand it through examples and see different approaches to solving the problem. A permutation is a...

5 minutes read.

What is interpreter in Java?

The programming language Java is platform-neutral. Therefore, can use Java on any platform that supports the Java processor. The Piece of software transforms the Java bytecode contained in the class...

5 minutes read.

Java Long Keyword

Long is a primitive data type in Java. To initilize variables, we implement the long keyword. It can also be applied to techniques. A 64-bit two's complement integer can put...

3 minutes read.

Java String trim() method

Java String trim() method returns String after eliminating leading and trailing spaces. Note:- Java String trim() method doesn't trim or omit middle spaces. Syntax: public String trim() Returns: It returns string with omitted leading and...

2 minutes read.