Obtain age from the date of birth in Java

7

I want to calculate the age from a date of birth in Date format. I've tried with this code that 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); 
    
asked by Oundroni 13.06.2016 в 15:23
source

5 answers

4

The Java 8 API for Dates and Hours is tremendous. I use it and it is my favorite. You can use JODA as it says to you @Alejandro Rangel Celis, which is compatible with previous 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 class Period :

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
    
answered by 13.06.2016 / 16:48
source
4

Review Joda , simplify dates and time calculations (Joda is also the basis of the new apis / date / date standard) Java time).

Java 8 has something very similar and it's worth reviewing.

Example

LocalDate birthdate = new LocalDate (1970, 1, 20);
LocalDate now = new LocalDate();
Years age = Years.yearsBetween(birthdate, now);

Here a similar question on the site in English.

    
answered by 13.06.2016 в 16:38
1

To work Dates in Java, it is recommended to use the library JODA . With it you can make this code retro-compatible since LocalDate comes from version 1.8 of Java.

    
answered by 13.06.2016 в 16:18
0
public static String getEdad(Date fechaNacimiento) {
    if (fechaNacimiento != null) {
        SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
        StringBuilder result = new StringBuilder();
        if (fechaNacimiento != null) {
            result.append(sdf.format(fechaNacimiento));
            result.append(" (");
            Calendar c = new GregorianCalendar();
            c.setTime(fechaNacimiento);
            result.append(calcularEdad(c));
            result.append(" años)");
        }
        return result.toString();
    }
    return "";
}

private static int calcularEdad(Calendar fechaNac) {
    Calendar today = Calendar.getInstance();
    int diffYear = today.get(Calendar.YEAR) - fechaNac.get(Calendar.YEAR);
    int diffMonth = today.get(Calendar.MONTH) - fechaNac.get(Calendar.MONTH);
    int diffDay = today.get(Calendar.DAY_OF_MONTH) - fechaNac.get(Calendar.DAY_OF_MONTH);
    // Si está en ese año pero todavía no los ha cumplido
    if (diffMonth < 0 || (diffMonth == 0 && diffDay < 0)) {
        diffYear = diffYear - 1;
    }
    return diffYear;
}
    
answered by 21.10.2016 в 21:01
-1
//declarar una fecha de nacimiento
LocalDate fechaNacimiento.of(1982, Month.June, 22);
//crear fecha de hoy para comparar
LocalDate fechaHoy = LocalDate.now();
//ahora comparar los años de las dos fechas y asi obtener la edad
int edad = fechaHoy.getYear() - fechaNacimiento.getYear();
    
answered by 13.09.2017 в 05:20