Reputation: 139
I have a instance of Java.Time.LocalTime
as startTime. After completion of a task I want to get the current time and get the difference of two in hours
.
int noOfHours = LocalTime.now() - startTime;
Upvotes: 3
Views: 2929
Reputation: 63405
Two choices, both involving java.time.temporal.ChronoUnit.HOURS
:
// use the until() method on LocalTime
long noOfHours = startTime.until(LocalTime.now(), ChronoUnit.HOURS);
// use the between() method on HOURS
long noOfHours = ChronoUnit.HOURS.between(startTime, LocalTime.now());
To convert long
to int
use Math.toIntExact(noOfHours)
.
Upvotes: 2
Reputation: 328737
You can use:
import static java.time.temporal.ChronoUnit.HOURS;
HOURS.between(startTime, LocalTime.now());
Upvotes: 5