Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to sum two times in Java, using LocalTime?

Example:

LocalTime time1 = LocalTime.of(12, 30);
LocalTime time2 = LocalTime.of(8, 30);
time1 + time2   // Doesn't work.
time1.plus(time2)   // Doesn't work.

I want to get the sum of the two times (12:30 + 8:30 = 21:00) in the format of (hours:minutes).

Any other suggestions?

like image 220
Valio Avatar asked Oct 25 '25 22:10

Valio


2 Answers

You are trying to add two LocalTime variables. This is wrong as a concept. Your time2 should not be a LocalTime, it should be a Duration. A duration added to a time gives you another time. A time subtracted from a time gives you a duration. It is all nice and logical. Adding two times together is not.

It is possible with some hacking to convert your time to a duration, but I would strongly advise against that. Instead, restructure your code so that time2 is a Duration in the first place.

like image 69
Mike Nakis Avatar answered Oct 27 '25 11:10

Mike Nakis


You can do the following...

LocalTime t1 = LocalTime.of(9, 0);  // 09:00
LocalTime t2 = LocalTime.of(2, 30); // 02:30
LocalTime total = t1.plusHours(t2.getHour())
                    .plusMinutes(t2.getMinute());  // 11:30
like image 22
Jefferson Ramos Avatar answered Oct 27 '25 12:10

Jefferson Ramos