I want to compare start date and end date. The start date always needs to be smaller than the end date. CompareTo () I encountered an error

4

When the end date is with the 00:00 time, it identifies that the start date is longer than the end date but it is not, the start date is still shorter.

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

Sample 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!");
   }
  }
   }
    
asked by anonymous 15.01.2017 / 01:13

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 because the day starts at zero hours and ends at 23:59 .

See 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 , since dataInicial occurred after dataFinal , so it is greater.

My recommendation is to see using the new API to compare dates . make this type of comparison (in this case LocalDateTime would be better than Date ).

    
15.01.2017 / 01:59