Calculate age per day, month and year

Asked

Viewed 13,820 times

5

I’m trying to calculate the age per 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 would be 22, 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;

    }
  • go wrong in what sense? which errors are presented?

  • Wrong because the displayed age is incorrect, for example. 14/06/1992 = 22 years. The result of this method is 23, would be 23 if the date of birth was greater than or equal to 15/06/1992

  • This is not directly related to your question, but I would change the function signature to getIdade(java.util.Date dataNasc, java.util.Date hoje = null) and if (hoje == null) { Calendar today = Calendar.getInstance(); } else { Calendar today = new GregorianCalendar(); today.setTime(hoje); }: this way, it is possible to write automatic tests for your function (you would spend a day "today" fixed to your function in the tests).

  • 1

    Behold that answer. The class Chronounit also supports YEARS and MONTHS. Finally, if you want to compute all three at once use the method Period.between.

  • Calculation of age in years, months and days:<br> http://forum.imasters.com.br/topic/552949-idade-em-javafx-em-anos-meses-e-days/

3 answers

6

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 as 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 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 like LocalDate, object that contains date only, does not contain time and does not display class time zone problems java.util.Date.

The method Period#between 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();
}

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 the type java.util.Date, we can perform the conversion to type LocalDate and again reuse the above routine:

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

Once again I remember that the insistence on using java.util.Date, java.util.Calendar and associated classes such as SimpleDateFormat and DateFormat often lead to problems in date manipulation and calculation due to time zone problems. This means 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.

  • 1

    Excellent reply @utluiz, I had even forgotten the time zone.

1


Try it this way:

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);
   }
  • Shouldn’t your method return something? Perhaps it would also be a good idea to add an example of what to call the method calculaIdade() correctly.

  • You’re absolutely right. Updated.

  • Thank you very much, I’ve already implemented.

-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;

     };
   }
}

Browser other questions tagged

You are not signed in. Login or sign up in order to post.