×

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

Java Integer hashCode() method

The hashCode()  method of Java Integer class returns a hash code for this Integer.  Syntax public int hashCode() public static int hashCode(int value)  Parameters The parameter ‘value’ represents a value whose hash code...

1 minute read.

Spliterator in Java 8

In this tutorial, we will understand the meaning of spliterator in java 8. It is just like any other iterator available in java used to traverse the elements of either...

4 minutes read.

Conditional operator in Java

In Java, there are around eight operators, and among them, three operators are used to evaluate the condition and decide the Result based on the Result of the evaluated condition. Below...

4 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Computing Digit Sum of all Numbers from 1 to n in Java

In this tutorial, we will discuss various methods to compute the sum of digits of all numbers beginning from 1 to n through a Java program. We will achieve it through...

7 minutes read.

Java Flags Enum

In a programming language, enumerations represent a group of named constants.For instance; the four suits in a deck of playing cards could be the enumerators Club, Diamond, Heart, and Spade,...

3 minutes read.

Number Pattern Programs in Java

Number Pattern Programs in Java: Number pattern programs are part of pattern programs. In the previous section, we have learned the approach to print the pattern program in Java. To...

6 minutes read.

String vs StringBuilder

String vs StringBuilder In this section, we will discuss the comparison between Java String and StringBuilder class. String In Java, a string is treated as an object that represents a sequence of characters....

4 minutes read.

String Concatenation in Java

In Java, it gathers a new String that combines several strings. Following are the manners to concatenate strings in Java: By + (String concatenation) operatorBy concat() method By + (String concatenation) operator Java...

4 minutes read.

Kong Java Client

Kong is an Organization Microservice Programming interface gateway. Kong gives an adaptable deliberation layer that safely oversees correspondence among clients and microservices by means of a Programming interface. Otherwise called...

6 minutes read.

Advantages and Disadvantages of Strings in Java

What is a String? Java is an object-oriented, platform-independent, high-level, general-purpose, and interpreted programming language.Sun Microsystems is known as the founder of java in 1991; the Java programming language was developed...

4 minutes read.

Java Math nextUp() Method

The nextUp() method of Math class returns the floating-point number adjacent to the argument in direction of the positive infinity. Syntax: public static double nextUp (double d)public static float nextUp (float f) Parameters: The...

2 minutes read.

Java String contains() method

contains() method returns true only if it contains the given sequence of characters otherwise it returns false. syntax: public boolean contains(CharSequence sequence) parameters: sequence : It is the sequence to be searched. Returns: It returns true...

1 minute read.

Enterprise Java Beans

One of the many Java APIs for the common development of corporate software is Enterprise Java Beans (EJB). An EJB, a server-side software component, contains the business logic of an...

4 minutes read.

Java Console

If there is a character-based console device connected to the active Java virtual machine, it can be accessed using methods provided by the Java.io.Console class. JDK 6 adds the Console...

3 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.

Java Enum Keyword

Definition: A data type in Java called Enum has a respect to supply of constants. The weekdays (SUN, MON, TUE, WED, THU, FRI, and SAT), directions (NORTH, SOUTH, EAST, and WEST),...

4 minutes read.

Java Viva Questions and Answers

Question: Explain Java programming language. Answer: It is a high-level programming language. This programming language is based on the principles of object-oriented programming. Large-scale applications can be developed by using this...

16 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Generic queue in Java

Before understanding how to implement a generic queue in java, one must know about generics and queue in java. Generics in Java Generics are parameterized types. The goal is to enable type...

6 minutes read.