3

I've looked at just about all the other posts pertaining to my question without finding a similar issue as mine.

I'm trying to get the time between two fields using this code.

LocalTime timeFrom = LocalTime.parse("16:00");
LocalTime timeTo = LocalTime.parse("00:00");

System.out.println(Duration.between(timeFrom,timeTo).toHours());

The issue I'm having is that the print out is negative 16 hours. What I want to accomplish is to get the amount of time from 4pm (which is 1600) to 12am (which is 00:00).

The result that I'm looking for would be 8 hours.

I have an idea of taking 1 minute from the 00:00, then getting the duration between those then just simply adding the 1 minute back to it, but I was thinking there must be an easier way.

kleopatra
  • 51,061
  • 28
  • 99
  • 211
exceptionsAreBad
  • 573
  • 2
  • 5
  • 17

2 Answers2

4

After pondering I feel like I was looking for a programmer solution instead of a simple one...

The answer to this is just adding 24 hours back to the negative result!

LocalTime timeFrom = LocalTime.parse("16:00");
LocalTime timeTo = LocalTime.parse("00:00");


long elapsedMinutes = Duration.between(timeFrom, timeTo).toMinutes();

//at this point Duration for hours is -16.

//checking condition
if(timeTo.toString().equalsIgnoreCase("00:00")){
   //condition met, adding 24 hours(converting to minutes)
   elapsedMinutes += (24 * 60);
}
long elapsedHours = elapsedMinutes / 60;
long excessMinutes = elapsedMinutes % 60;


System.out.println("Hours: " + elapsedHours);
System.out.println("Minutes: " + excessMinutes);
exceptionsAreBad
  • 573
  • 2
  • 5
  • 17
1

I propose to check if the result is negative, then you don't limit the code to check for exact string equality, and 00:01 will still come out 8 hours:

import java.time.Duration;
import java.time.LocalTime;

public class StackOverflowTest {
  public static void main(String[] args) {
    String from = "16:00";
    String to   = "00:01";

    LocalTime timeFrom = LocalTime.parse(from);
    LocalTime timeTo = LocalTime.parse(to);

    Duration duration = Duration.between(timeFrom,timeTo);
    if (duration.isNegative()) duration = duration.plusDays(1);

    System.out.println(duration.toHours());
  }
/*
Prints:
8
*/
}

Or perhaps or more reader-friendly option:

...snip
Duration duration;
if (timeFrom.isBefore(timeTo)) {
  duration = Duration.between(timeFrom,timeTo);
} else {
  duration = Duration.between(timeFrom,timeTo).plusDays(1);
}
Scratte
  • 3,056
  • 6
  • 19
  • 26