I'm developing an app in which I'm using Java8 Time. I'm facing an issue.
Let's say Time A is 08:00 and Time B is 17:00, so the difference of between these two times will be 9h which in my case is correct, but if Time A is 18:00 and Time B is 02:00 it should be 8h, but in my case my program is returning -16. Kindly someone guide me how to solve this.
My code:
@Test
public void testTime()
{
DateTimeFormatter format = DateTimeFormatter.ofPattern("HH:mm");
String s = "18:00";
String e = "02:00";
// Parse datetime string to java.time.LocalDateTime instance
LocalTime startTime = LocalTime.parse(s, format);
LocalTime endTime = LocalTime.parse(e, format);
String calculatedTime = ChronoUnit.HOURS.between(startTime, endTime)%24 + ":"
+ ChronoUnit.MINUTES.between(startTime, endTime)%60;
System.out.println(calculatedTime);
}
check if the startTime is after endTime and swap the opernads if required:
Why not use the
Duration
class? It’s meant for situations like yours.This prints the duration in ISO 8601 format:
To format it in Java 8:
This prints
To format in Java 9 (not tested):
You have to calculate time differences modulo
24
. So take the difference as you already do and then compute it modulo24
. Note that in Java-16%24
would return-16
so what you really need to do is the following:which always return a positive result.
If the time difference comes out negative, then add 24.
Simples!
(Obviously this will ignore overnight changes to daylight saving time, so your best bet really is to do this properly using time duration objects. That said though, you'll then need to know more about the dates associated with the two times.)