Compare dates and validate only the same year

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, show the message "ok". 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;
        }           

    }
    
asked by anonymous 27.06.2017 / 19:27

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:

1st : I declare a SimpleDateFormat with the pattern ("yyyy") to use the format () method, which receives a Date and returns a String with the date value passed in the last pattern case, only the year of the date. 'yyyy')

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

3rd : I did the test to know if these variables are equivalent or not, if they are, the years are the same, otherwise they are not.

    
28.06.2017 / 05:30