Compare dates and validate only the same year

Asked

Viewed 481 times

1

In my component p:calendar there are two date ranges dtInicial and dtFinal in the Managed bean I need to compare only the years and validate. If it is the same year, display the "ok" message. Otherwise, "different years".


private int getYear(Date date) {
    Calendar calendar = new GregorianCalendar();
    calendar.setTime(date);
    return calendar.get(Calendar.YEAR);
}

    boolean hasInterval = sourceReq.getDtInicial() != null 
            && sourceReq.getDtInicial() != null;
    if (hasInterval){
        int dtIni = getYear(sourceReq.getDtInicial());
        int dtFin = getYear(sourceReq.getDtFinal());

        if (dtIni != dtFin){
            showErrorMessage("Favor informar o mesmo Ano para Pesquisa.", true);
            return false;
        }           

    }
  • jsp? Can you add as is your code?

  • Poisé Marcos, checking your doubt I figured it would be jsp too.

  • are 2 <p:calendar> one for dtInitial and one for dtFinal?

  • if it is, this component of the first faces works with the class Date of the java.util package.

1 answer

0

what you could do was

SimpleDateFormat formatter = new SimpleDateFormat("yyyy");
String dataInicial = formatter.format(dtInicial)
String dataFinal = formatter.format(dtFinal)
if(dataInicial.equals(dataFinal)){
   //Coloque aqui sua mensagem de ok, já que os anos das duas datas são iguais
}else{
   //Coloque aqui seu tratamento para mensagem diferente
}

Explaining what I did:

first : I declared a Simpledateformat with Pattern("yyyy") to use the format() method, which receives a Date and returns a String with the value of the date passed in the last Pattern (in this case, only the year of the date. 'yyyy')

2nd : assigns the return of the format() method to the start and start date variables with their respective parameters.

: I did the test to see if these variables are equivalent or not, if they are, the years are equal, otherwise, they are not.

Browser other questions tagged

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