I want to define a unit Time for example, 12 minutes or 25 minutes, for know how many unit Times there are between 2 LocalTime in Java.
For Example, if I defined 15 minutes like unit time, between 8:00 and 10:00, I should get 8 times.
You can use Duration class to get the duration between two LocalTime values. Then you can calculate the custom time units yourself:
int minutesUnit = 15;
LocalTime startTime = LocalTime.of(8, 0);
LocalTime endTime = LocalTime.of(10, 0);
Duration duration = Duration.between(startTime, endTime);
long unitsCount = duration.toMinutes() / minutesUnit;
System.out.println(unitsCount);
This prints 8
.
If you have different time units you could break the duration down to millis and calculate the result:
long millisUnit = TimeUnit.MINUTES.toMillis(15);
// ...
long unitsCount = duration.toMillis() / millisUnit;
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With