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.