Reputation: 17
Right now, I can get the hours between two LocalTime times like this:
public long getHours(){
return ChronoUnit.HOURS.between(this.timeIn, this.timeOut);
}
But the result is only the number of hours. What I want is to also include the minutes as well. So for example if 5 hours and 30 minutes passed the result to be 5.30.
EDIT: For example timeIn is 10:00:00 and time out is 15:30:00. I want the hours and minutes between these two times
Upvotes: 0
Views: 735
Reputation: 16498
You can use the Duration.between
method from the java.time API:
public static Duration getDuration(){
LocalTime timeIn = LocalTime.now();;
LocalTime timeOut = timeIn.plusHours(5).plusMinutes(30).plusSeconds(23);
return Duration.between(timeIn, timeOut);
}
Returned for above example:
PT5H30M23S
That text is in standard ISO 8601 format.
To format it differently use the methods toXXXPart()
from the Duration
class:
public static String format(Duration duration) {
return String.format("%02d:%02d:%02d", duration.toHoursPart(), duration.toMinutesPart(), duration.toSecondsPart());
}
A sample output with the same above example:
System.out.println(format(getDuration()));
prints
05:30:23
Upvotes: 5