I want to compare start date and end date. The start date always needs to be less than the end date. Compareto() an error came to me

Asked

Viewed 7,176 times

5

When the final date is with the time of 00:00, it identifies that the initial date is greater than the final date only it is not, the initial date remains smaller.

When I set the final date 14/01/2017 23:45 the method returns me -1. But if I put the final date in effect 14/01/2017 00:45 it returns me 1. This is wrong. How can I resolve this issue?

Example class:

public class Hora {
public static void main(String[] args) {

Date dataInicial = null;
Date dataFinal = null;
String datafinal = "14/01/2017 00:45";

//Aqui eu pego a hora atual.
Calendar c = Calendar.getInstance();
dataInicial = c.getTime();
//System.out.println(dataInicial);

SimpleDateFormat sdf = new SimpleDateFormat("dd/MM/yyyy HH:mm");

try { 

  dataFinal = sdf.parse(datafinal);

} catch (Exception e) {

}       
//datafinal = sdf.format(dataFinal);

    System.out.println(dataInicial.compareTo(dataFinal));


   if(dataInicial.compareTo(dataFinal) < 0){
    System.out.println("tudo ok!");
   }
  }
   }

1 answer

6


The result is correct, because if dataInicial is 14/01/2017 23:45 and dataFinal is 14/01/2017 00:00, dataInicial is greater than dataFinal, for the day begins at zero hours and ends at 23:59.

Take this example:

Date dataInicial, dataFinal;
String strDataInicial = "14/01/2017 23:45";
String strDataFinal = "14/01/2017 00:00";

SimpleDateFormat sdf1 = new SimpleDateFormat("dd/MM/yyyy HH:mm");
SimpleDateFormat sdf2 = new SimpleDateFormat("dd/MM/yyyy HH:mm");

dataFinal = sdf1.parse(strDataFinal);
dataInicial = sdf2.parse(strDataInicial);

System.out.println(dataInicial.compareTo(dataFinal));
System.out.println(dataInicial.after(dataFinal));

The return will be 1 and true, for the dataInicial occurred after the dataFinal, so she’s bigger.

My recommendation is that you see the possibility of use the new API to compare dates, there are more possibilities to make this kind of comparison (in this case LocalDateTime would be better than the Date).

  • 1

    That’s all I needed....

Browser other questions tagged

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