Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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.

like image 472
Brayme Guaman Avatar asked Dec 11 '22 03:12

Brayme Guaman


1 Answers

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;
like image 144
Samuel Philipp Avatar answered Dec 28 '22 22:12

Samuel Philipp