Calculate age by day, month and year

I'm trying to calculate the age by day, month and year but I'm not getting it. I followed some examples but they all go wrong too. For example if the date of birth is 14/06/1992 this method returns 23 years and the correct one would be 22, it would only be 23 years if the date of birth was greater than or equal to 15/06/1992

public static int getIdade(java.util.Date dataNasc) {

        Calendar dateOfBirth = new GregorianCalendar();

        dateOfBirth.setTime(dataNasc);

        // Cria um objeto calendar com a data atual

        Calendar today = Calendar.getInstance();

        // Obtém a idade baseado no ano

        int age = today.get(Calendar.YEAR) - dateOfBirth.get(Calendar.YEAR);

        dateOfBirth.add(Calendar.YEAR, age);

        // se a data de hoje é antes da data de Nascimento, então diminui 1.

        if (today.before(dateOfBirth)) {

            age--;

        }

        return age;

    }
 5
Author: DiegoAugusto, 2015-06-15

3 answers

Tries like this:

public static int calculaIdade(java.util.Date dataNasc) {

    Calendar dataNascimento = Calendar.getInstance();  
    dataNascimento.setTime(dataNasc); 
    Calendar hoje = Calendar.getInstance();  

    int idade = hoje.get(Calendar.YEAR) - dataNascimento.get(Calendar.YEAR); 

    if (hoje.get(Calendar.MONTH) < dataNascimento.get(Calendar.MONTH)) {
      idade--;  
    } 
    else 
    { 
        if (hoje.get(Calendar.MONTH) == dataNascimento.get(Calendar.MONTH) && hoje.get(Calendar.DAY_OF_MONTH) < dataNascimento.get(Calendar.DAY_OF_MONTH)) {
            idade--; 
        }
    }

    return idade;
}

}

You can execute as follows:

public static void main(String[] args) throws ParseException
   {
      SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy");
      Date dataNascimento = sdf.parse("15/11/1979"); 
      int idade = calculaIdade(dataNascimento);
      //A idade é:
      System.out.println(idade);
   }
 1
Author: bruno, 2015-06-15 17:05:07

First of all, the use of classes like java.util.Date and java.util.Calendar should be avoided, being alternative library classes Joda-Time or classes like LocalDate and LocalDateTime, in addition to the rest of the date and Time API java.time present from Java 8.

Using the Java 8 API, mentioned above, we can use the class Period to calculate the time interval between two dates, including the amount of years. Thus, a possible implementation of a routine would be as follows:

public static int idade(final LocalDate aniversario) {
    final LocalDate dataAtual = LocalDate.now();
    final Period periodo = Period.between(aniversario, dataAtual);
    return periodo.getYears();
}

The date is of type LocalDate, an object that contains only date, does not contain time, and does not present the time zone problems of Class java.util.Date.

The Period#between method calculates the period between the birthday date and the current date created with LocalDate#now.

Finally, the routine returns the number of years of the period.

After understanding how the method works, we could abbreviate it without the auxiliary variables as follows:

public static int idade(final LocalDate aniversario) {
    return Period.between(aniversario, LocalDate.now()).getYears();
}

Se, for some reason, the program needs to use distinct variables for day, month and year, just apply LocalDate.of to create a date from the values and reuse the above routine:

public static int idade(final int dia, final int mes, final int ano) {
    return idade(LocalDate.of(ano, mes, dia));
}

If, for another reason, the program needs to use dates of type java.util.Date, we can perform the conversion to type LocalDate and, once again, reuse the above routine:

public static int idade(final Date dataAniversario) {
    return idade(LocalDateTime.ofInstant(dataAniversario.toInstant(), ZoneOffset.UTC).toLocalDate());
}

Again I recall that the insistence on using java.util.Date, java.util.Calendar and associated classes such as SimpleDateFormat and DateFormat often lead to problems in handling and calculating dates due to time zone issues. This causes that in periods affected by Daylight Saving Time, for at least one hour, birthdays have the wrong value. out other more serious problems when adding and subtracting time.

 6
Author: utluiz, 2016-10-26 00:34:20
public class Idade {
    GregorianCalendar calendar = new GregorianCalendar();
    public int idade;
    public final int anoatual= calendar.get(GregorianCalendar.YEAR);
    public final int mesatual = calendar.get(GregorianCalendar.MONTH);
    public final int diaatual = calendar.get(GregorianCalendar.DAY_OF_MONTH); 
    public int anoNasc;
    public int mesNsac;
    public int diaNasc;

    public Idade(int diaNasc, int mesNsac, int anoNasc ) {
        this.diaNasc = diaNasc;
        this.mesNsac = mesNsac;
        this.anoNasc = anoNasc;
    }

    public void calculandoIdade() {
       Date data = new Date(System.currentTimeMillis());
        System.out.println(data);

        System.out.println("                                          Data:"+this.diaatual+"/"+(this.mesatual+1)+"/"+this.anoatual);
        if (this.diaNasc>31 || this.mesNsac > 12 || this.diaatual>31 || this.mesatual > 12){
            System.out.println("Você digitou alguma data errada confira novamente!");
                    }else{System.out.println("Você nasceu em: "+this.diaNasc+"/"+this.mesNsac+"/"+this.anoNasc);}

        if (this.diaNasc>31 || this.mesNsac > 12 || this.diaatual>31 || this.mesatual > 12){
            System.out.println("Você digitou alguma data errada confira novamente!");
          }else if(this.mesNsac < this.mesatual ){
            this.idade = this.anoNasc - this.anoatual;
            System.out.println("Idade: "+this.idade+" anos");
        }else if (this.mesNsac > this.mesatual){
            this.idade = this.anoatual - this.anoNasc - 1;
            System.out.println("Idade: "+this.idade+" anos");
      }else if (this.mesNsac == this.mesatual && this.diaNasc == this.diaatual ){
            this.idade = this.anoatual - this.anoNasc;
            System.out.println("Idade: "+this.idade+" anos");
            System.out.println("Parabens!! Feliz Aniversário");
        }else if(this.mesNsac == this.mesatual && this.diaNasc < this.diaatual){
            this.idade = this.anoatual - this.anoNasc - 1;
            System.out.println("Idade: "+this.idade+" anos");
        }else if(this.mesNsac == this.mesatual && this.diaNasc > this.diaatual){
            this.idade = this.anoatual - this.anoNasc;

     };
   }
}
 -1
Author: Samuel Nunes, 2018-02-11 18:23:40