Sum of time with result more than 24 hours

athosbr99 :

Suppose the following snippet:

LocalTime test = LocalTime.of(21, 14);
test.plusHours(5);

The result would be, normally, 02:14 but I want to sum beyond the 24 hour limit, so the result would be 26:14.

In this case I have a field that an user can input how much time it spent on a task. However I have to work with hours (eg 48 hours) instead of days (eg 2 days and 4 hours).

Is there a way that I can achieve that within the java.time API? If not, what can I do to achieve that? I am using Java 8, with Spring Boot and Hibernate to map the database.

ernest_k :

java.time.Duration

You’re using the wront data type for the value. You need a Duration. Duration is the time-level counterpart of Period:

A time-based amount of time, such as '34.5 seconds'.

Duration durationTaken = Duration.of(5, ChronoUnit.HOURS);

If you want to relate that to a date concept, such as to compute the end time, you can plus durations to date/time types:

LocalTime endTime = test.plus(durationTaken); //02:14

And you can do that with LocalDateTime too:

LocalDateTime startTime = LocalDateTime.of(LocalDate.now(), test); //2019-02-07T21:14

//add the duration:
LocalDateTime endDate = startTime.plus(durationTaken); //2019-02-08T02:14

Guess you like

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