Java JSP return of age

Asked

Viewed 213 times

0

I redid the class Idade and made a test with console and worked right the part.

But JSP is showing error and I don’t know how it will do and how I will put in JSP to return age.

//Classe Idade.java
import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.Month;
import java.time.Period;
import java.time.format.DateTimeFormatter;
import java.time.format.FormatStyle;
import java.time.temporal.TemporalAccessor;
import java.time.temporal.TemporalQuery;
import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.Locale;
import java.util.Scanner;

public class Idade {

    private int idade;

    public int getIdade() {
        return idade;
    }

    public void setIdade(int idade) {
        this.idade = idade;
    }

    public int calcularIdade(Date dataNascimento) {
        GregorianCalendar dataHoje = new GregorianCalendar();
        int diaAtual = 0, mesAtual = 0, anoAtual = 0; 
        diaAtual = dataHoje.get(Calendar.DAY_OF_MONTH);
        mesAtual = dataHoje.get(Calendar.MONTH) + 1;
        anoAtual = dataHoje.get(Calendar.YEAR);
        SimpleDateFormat formatador = new SimpleDateFormat("dd/MM/yyyy");
        String dtNasc = formatador.format(dataNascimento);
        String diaNasc = dtNasc.substring(0, 2);
        String mesNasc = dtNasc.substring(3, 5);
        String anoNasc = dtNasc.substring(6, 10);
        int diaNascimento = Integer.parseInt(diaNasc);
        int mesNascimento = Integer.parseInt(mesNasc);
        int anoNascimento = Integer.parseInt(anoNasc);
        idade = anoAtual - anoNascimento;
        if (mesAtual < mesNascimento) {
            idade--;
        } else if(diaAtual < diaNascimento){
            idade--;
        }
        return idade;
    }
}

Below is the JSP fragment that is showing error when opening the Tomcat with the page.

<tr>
    <td>Data de Nascimento:</td>
    <td><input type="date" name="dataNascimento"/></td>
</tr>
<tr>
    <%
    Date nascimento= new Date(request.getParameter("dataNascimento"));
    int idader = new Idade().calcularIdade(nascimento);
    %>
    <td>Idade:</td>
    <td><input type="text" name="idade" maxlength="3" size="1" <%=idade.getIdade()%>/></td> // Mensagem de erro: idade cannot be resolved
</tr>
<tr>

2 answers

0

Import the Age class into your jsp file

<%@ page import ="package.Idade" %>

Substitute package by way of the package containing the Age class.

0

I don’t know if it was a typo posting, but look at this line:

int idader = new Idade().calcularIdade(nascimento);
         ^

You declared the variable idader (with a r at the end) and then tried to use idade.getIdade() (idade, without the r). That’s why you made the mistake of "age cannot be resolved".

This type of question is usually closed because it is just a typo (if you confirm that this is the case), but I will take advantage and talk a little about the calculation of age.


You are creating the date with:

new Date(request.getParameter("dataNascimento"));

But I don’t think that’s gonna work. Um input type=date has its value returned in format ISO 8601, that is to say, "yyyy-mm-dd". By passing this on to the builder of Date, make a mistake.

Another thing is, for your sake imports, you can see that you are already using Java >= 8, which has the API java.time. If you already have this API available, there is no reason to mix with the old (Date, Calendar and SimpleDateFormat). The new API is far superior and corrects several of the problems of the previous.

That said, the code for calculating age is as simple as that:

import java.time.LocalDate;
import java.time.temporal.ChronoUnit;

// getParameter retorna a data no formato aaaa-mm-dd
// LocalDate.parse entende esse formato
LocalDate dtNasc = LocalDate.parse(req.getParameter("dataNascimento"));

public int calcularIdade(LocalDate dataNascimento) {
    return (int) ChronoUnit.YEARS.between(dataNascimento, LocalDate.now());
}

And only. Again, if you have the classes of the java.time available, there is no reason to mix them with Date and Calendar (unless there is legacy code with these classes and you cannot change it, for example - but in new code, you have no reason to use the old API, the new one being is much better).

Notice I made one cast for int, since the method between returns a long. As you are working with ages, you will hardly burst the maximum value of a int (that is more than 2 billion), then it’s safe to do this cast. Incidentally, the difference between minimum and maximum values of a LocalDate is less than 2 billion, then use LocalDate in your calculations, will not exceed the value of int.


There is a corner case in this calculation. Let’s assume that the person was born on February 29, 2000.

If today was February 28, 2019, would the person have turned 19? Or do we still consider that she is 18? The API considers that she is 18:

LocalDate dataNascimento = LocalDate.of(2000, 2, 29);
LocalDate hoje = LocalDate.of(2019, 2, 28);
System.out.println(ChronoUnit.YEARS.between(dataNascimento, hoje)); // 18

This happens because the method between always round it down. If the start date is 01/10/2018 and the end date is 01/09/2019, the difference in years is zero (even if one day is missing and technically the difference is 0.99... years, the result is rounded down). Only from 01/10/2019 is it considered that the difference is 1 year.

That’s why the above example returns 18, not 19. It’s up to you to decide what to do in this specific case.

Browser other questions tagged

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