Java method that returns difference in hours

Asked

Viewed 601 times

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

  • You can turn the dates into timeInMillis subtract the largest by the smallest and then convert into hours, simpler way. = D

  • Okay, thanks for the tip William.

3 answers

4

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

How come you don’t have the PM/AM to differentiate morning and afternoon, the Java is "confused" and when interpreting 12:45, he thinks it’s 00:45

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

That way we’ll have 03/01/2018 23:00 - 03/01/2018 00:00 = -1 hour. That’s why your returnee is returning -1.

Example: https://ideone.com/GosexI

  • Thank you very much Valdeir! I was suspicious of this, but I was not understand how he was interpreting this difference of 12/24hs.

3


Change the line:

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

for

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

According to call parameters

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

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

  • Thank you very much Rafael! That’s right. Thanks!

2

Java 8 added new classes for handling issues such as date difference and event duration in the JSR-310 specification. Below is an example of the class Duration, of 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 are not using Java 8, there is a backport for Java 6, 7 and Android.

  • Thanks for the help!!

Browser other questions tagged

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