You have two time (H:M:S) as string and you want to create sum of them. What will you do?

Let, the strings are:

String timeDuration1 = "104:30:00";
String timeDuration2 = "15:59:10";

Result of above two should be 120:29:10.

Let’s do it. We will be using Duration of java.time which is with us since Java 8.

String timeDuration1 = "104:30:00";
String timeDuration2 = "15:59:10";

String[] values1 = timeDuration1.split(":");
String[] values2 = timeDuration2.split(":");

Duration duration = Duration.ofHours(Integer.parseInt(values1[0]));

duration = duration.plusMinutes(Integer.parseInt(values1[1]));
duration = duration.plusSeconds(Integer.parseInt(values1[2]));
Duration duration2 = Duration.ofHours(Integer.parseInt(values2[0]));
duration2 = duration2.plusMinutes(Integer.parseInt(values2[1]));
duration2 = duration2.plusSeconds(Integer.parseInt(values2[2]));
Duration totalDuration = duration.plus(duration2);
long totalDurationInSeconds = totalDuration.toSeconds();
String totalTimeDuration = String.format("%02d:%02d:%02d", totalDurationInSeconds / 3600, (totalDurationInSeconds % 3600) / 60, totalDurationInSeconds % 60);
System.out.println(totalTimeDuration);

The output is 120:29:10.

Previous ArticleNext Article
Abdullah-Al-Tareq, The Search Engineer of Rokomari.com.

Leave a Reply

Your email address will not be published. Required fields are marked *