How many unitTime(10 mins, half hour) there are between 2 localTime? Java 8

Brayme Guaman :

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.

Samuel Philipp :

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;

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=72274&siteId=1