calculate age from date of birth in java

Here we are calculate age from date of birth in java from Local Date method.To parsing date use DateTimeFormatter where they first checking which format is Date of Birth.Period class use to measure times in years,months and days from period class betoween method take dob and current date and return date. getYears method return the number of age.
From if condition check age and return the status and depend of age.

				
					import java.time.LocalDate;
import java.time.Period;
import java.time.format.DateTimeFormatter;

public class CheckValidAge {
	public static void main(String[] args) {
		boolean s = isValiAge("03/10/1984");
		System.out.println("user age is valid:- " + s);
	}

	public static boolean isValiAge(String dob) {
		boolean result = false;
		StringBuilder sb = new StringBuilder();
		LocalDate userDob = LocalDate.parse(dob, DateTimeFormatter.ofPattern("dd/MM/yyyy"));
		int age = Period.between(userDob, LocalDate.now()).getYears();
		System.out.println("User age is:- " + age + " years");
		if (age >= 18 && age <= 99) {
			sb.append("user age is between 18 and 99 years old");
			result = true;
		} else {
			sb.append("user age is not between 18 and 99 years old");
			result = false;
		}
		System.out.println(sb);
		return result;
	}
}
				
			

Output :-
User age is:- 38 years
user age is between 18 and 99 years old
user age is valid:- true

Leave a Comment

Your email address will not be published. Required fields are marked *