Calculate Age in Java
In this example, I’ll show you How to Calculate age from Date of Birth in Java.
Program Code:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 | import java.time.LocalDate; import java.time.Period; public class JavaExample { public static Period CalculateAge(LocalDate dateNow, LocalDate birthDate) { LocalDate lb = birthDate; LocalDate now = dateNow; Period diff = Period.between(lb,now); //difference between the dates return diff;//return calculated diff; } public static void main(String[] args) { LocalDate ldate = LocalDate.of(1983, 06, 10); LocalDate lnow = LocalDate.now(); Period diff = CalculateAge(lnow,ldate); System.out.println(diff.getYears() + " years\n" + diff.getMonths() + " months\n" + diff.getDays() + " days "); } } |
Output:
1 2 3 4 5 | 36 years 6 months 11 days |