Java Calculate Age from ZonedDateTime of Birth
Tags: Java ZonedDateTime DateUtil
In this Java tutorial, we learn how to write Java program to calculate someone’s age based on their birthday as a ZonedDateTime object in Java programming language.
How to calculate age from ZonedDateTime of birth in Java
At this first step, we create a new Java class named DateUtil, and implement a new static method named getAge(ZonedDateTime birthday), this method to calculate the number of age from a given ZonedDateTime value and current system date then return age as an integer value.
DateUtil.java
import java.time.ZonedDateTime;
import java.time.temporal.ChronoUnit;
public class DateUtil {
/**
* This method to calculate number of age from given birthday ZonedDateTime value.
* @param birthday the ZonedDateTime of birth
* @return number of age
*/
public static int getAge(ZonedDateTime birthday) {
ZonedDateTime today = ZonedDateTime.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 given ZonedDateTime value in Java program.
GetAgeFromZonedDateTimeExample.java
import java.time.ZonedDateTime;
public class GetAgeFromZonedDateTimeExample {
public static void main(String... args) {
ZonedDateTime birthday = ZonedDateTime.parse("1988-07-11T00:00:00.00+07:00[Asia/Bangkok]");
// Calculate Age from ZonedDateTime of Birth
int age = DateUtil.getAge(birthday);
System.out.println("Today: " + ZonedDateTime.now());
System.out.println("ZonedDateTime of birth: " + birthday);
System.out.println("Age: " + age);
}
}
Today: 2022-08-19T00:05:06.483218300+07:00[Asia/Bangkok]
ZonedDateTime of birth: 1988-07-11T00:00+07:00[Asia/Bangkok]
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