Abhay
Abhay

Reputation: 139

how to get number of hours between two Java.time.LocalTime instances

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

Answers (2)

JodaStephen
JodaStephen

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

assylias
assylias

Reputation: 328737

You can use:

import static java.time.temporal.ChronoUnit.HOURS;

HOURS.between(startTime, LocalTime.now());

Upvotes: 5

Related Questions