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