Calculate age by day, month and year

4

I'm trying to calculate the age by day, month, and year but I can not. I followed some examples but everyone goes 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;

    }
    
asked by anonymous 15.06.2015 / 16:25

3 answers

1

Try 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 run 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);
   }
    
15.06.2015 / 18:47
4

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 such as LocalDate and LocalDateTime , in addition to the rest of the datetime API java.time present from Java 8.

Using the Java 8 API mentioned above, we can use the Period to calculate the time interval between two dates, including the number 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 , object that contains only date, does not contain time and does not display the time zone problems of class java.util.Date .

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

Finally, the routine returns the number of years in 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();
}

If, for some reason, the program needs to use different 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());
}

I again remember that insisting on 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 problems. This causes the birthdays to have the incorrect value in periods affected by daylight saving time for at least one hour. other more serious problems by adding up and subtracting time.

    
26.10.2016 / 02:34
-1
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;

     };
   }
}
    
11.02.2018 / 18:17