Java method that returns difference in hours

1

Why is the method below returning -1? It should return the difference in hours between two dates.

public int diferencaHoras(String h1, String h2) throws ParseException{

     DateFormat df = new SimpleDateFormat ("dd/MM/yyyy hh:mm");

     Date d1 = df.parse (h1);
     Date d2 = df.parse (h2);

    long diff = d1.getTime() - d2.getTime();
    int diffHours = (int) (diff / (60 * 60 * 1000) % 24);

    return diffHours;
}

If I call the method with the parameters:

diferencaHoras("02/01/2018 23:00", "03/01/2018 12:00");

returns -1

    
asked by anonymous 09.01.2018 / 03:47

3 answers

3

Change the line:

DateFormat df = new SimpleDateFormat ("dd/MM/yyyy hh:mm");

by

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

According to call parameters

  

DifferenceHours ("02/01/2018 23:00", "03/01/2018 12:00");

The result will be -13, since the higher value date is after the operator.

    
09.01.2018 / 13:35
4

The error in your code is in pattern of the date. In Java , hh:mm means: "Hours from 1 to 12: minutes from 0 to 59".

As you do not have PM/AM to differentiate morning and afternoon, Java gets "confusing" and when interpreting 12:45 , it thinks it is 00:45

Your code is converting 03/01/2018 12:00 to 03/01/2018 00:00

That way we will have 03/01/2018 23:00 - 03/01/2018 00:00 = -1 hour. So your returned is returning -1 .

Example: link

    
09.01.2018 / 05:35
2

Java 8 added new classes for handling issues such as the difference between dates and event length in the JSR-310 specification. Here is an example of the Duration class of the specification:

import java.time.Duration;

DateTimeFormatter f = DateTimeFormatter.ofPattern("dd-MM-yyyy HH:mm:ss");

LocalDateTime dt1= LocalDateTime.parse("01-01-2018 10:30:00", f);
LocalDateTime dt2= LocalDateTime.parse("08-01-2018 16:00:00", f);

long diferencaMili = Duration.between(dt1, dt2).toMillis();
long diferencaSeg = Duration.between(dt1, dt2).getSeconds();
long diferencaMin = Duration.between(dt1, dt2).toMinutes();

If you're not using Java 8, there's a backport for Java 6, 7 and Android.

    
09.01.2018 / 14:00