Get age from date of birth in Java

Question:

I want to calculate age from a date of birth in Date format. I have tried this code which seems to work fine, but is it the most convenient way?

 LocalDate hoy = LocalDate.now();   
 LocalDate nacimiento = usuarioActivo.getFechaNacimiento().toInstant().
           atZone(ZoneId.systemDefault()).toLocalDate(); 
 long edad = ChronoUnit.YEARS.between(nacimiento, hoy); 

Answer:

The Java 8 API for Dates and Times is tremendous. I use it and it is my favorite. You can use JODA as @Alejandro Rangel Celis tells you, which is compatible with older versions of Java.

Java 8

The way you have it is valid, but not entirely correct because you do not take into account the months. For this you can use the Period class:

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

// 01/01/2000
DateTimeFormatter fmt = DateTimeFormatter.ofPattern("dd/MM/yyyy");
LocalDate fechaNac = LocalDate.parse("15/08/1993", fmt);
LocalDate ahora = LocalDate.now();

Period periodo = Period.between(fechaNac, ahora);
System.out.printf("Tu edad es: %s años, %s meses y %s días",
                    periodo.getYears(), periodo.getMonths(), periodo.getDays());

Exit:

Tu edad es: 22 años, 9 meses y 29 días
Scroll to Top