Java Calculate Age from Instant of Birth
Tags: Java Instant DateUtil
In this Java tutorial, we learn how to calculate someone’s age based on their birthday as an Instant object in Java programming language.
How to calculate age from Instant of birth in Java
At this first step, we implement a new Java class named DateUtil, and implement a static method named getAge(Instant birthday), in this method we calculate the number of age from given Instant object and current system date and return number of age as an integer value.
DateUtil.java
import java.time.Instant;
import java.time.LocalDateTime;
import java.time.ZoneId;
import java.time.temporal.ChronoUnit;
public class DateUtil {
/**
* This method to calculate number of age from given birthday Instant value.
* @param birthday the Instant of birth
* @return number of age
*/
public static int getAge(Instant birthday) {
LocalDateTime birthdayLocalDateTime = LocalDateTime.ofInstant(birthday, ZoneId.systemDefault());
LocalDateTime today = LocalDateTime.now();
int age = (int)ChronoUnit.YEARS.between(birthdayLocalDateTime, today);
return age;
}
}
In the following example Java code, we learn how to use the DateUtil class above to calculate age with a given Instant object in Java program.
GetAgeFromInstantExample.java
import java.time.Instant;
public class GetAgeFromInstantExample {
public static void main(String... args) {
Instant birthday = Instant.parse("1988-07-11T00:00:00.00Z");
// Calculate Age from Instant of Birth
int age = DateUtil.getAge(birthday);
System.out.println("Today: " + Instant.now());
System.out.println("Instant of birth: " + birthday);
System.out.println("Age: " + age);
}
}
Today: 2022-08-18T16:44:40.330145800Z
Instant of birth: 1988-07-11T00:00:00Z
Age: 34
Happy Coding 😊
Related Articles
Java Calculate Age from Date of Birth
Java Calculate Age from Calendar of Birth
Java Calculate Age from LocalDate of Birth
Java Calculate Age from LocalDateTime of Birth