Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Sum of time with result more than 24 hours

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.

like image 520
athosbr99 Avatar asked Dec 14 '22 13:12

athosbr99


2 Answers

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
like image 74
ernest_k Avatar answered Dec 23 '22 20:12

ernest_k


To specify how long a task takes, use Duration:

Duration initialDuration = Duration.ofHours(21).plusMinutes(34);
Duration afterFurtherWork = initialDuration.plusHours(5);
System.out.printf("Total duration was %2d hours and %02d minutes.%n",
        afterFurtherWork.toHours(), afterFurtherWork.toMinutesPart());

Update: as Ole V.V. points out, toMinutesPart was added in Java 9. If still using Java 8, use toMinutes()%60.

like image 25
DodgyCodeException Avatar answered Dec 23 '22 18:12

DodgyCodeException