Find Duration in Hours and Minutes Between Two Dates in Java
Learn how to calculate the duration in hours and minutes between two dates using Java.
The following Java code demonstrates how to find the duration in hours and minutes between two dates:
import java.math.BigDecimal; import java.math.RoundingMode; import java.time.Duration; import java.time.LocalDateTime; import java.time.format.DateTimeFormatter; public class DurationExample { public static void main(String[] args) { DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss"); String startDateTimeStr = "2021-05-10 11:50:10"; LocalDateTime startDateTime = LocalDateTime.parse(startDateTimeStr, formatter); String endDateTimeStr = "2021-05-10 13:54:45"; LocalDateTime endDateTime = LocalDateTime.parse(endDateTimeStr, formatter); String duration = getDurationBetweenDates(startDateTime, endDateTime); System.out.println(duration); } public static final String getDurationBetweenDates( LocalDateTime startDateTime, LocalDateTime endDateTime) { Duration duration = Duration.between(startDateTime, endDateTime); StringBuilder builder = new StringBuilder(); if (duration.toMinutes() < 60) { builder.append(duration.toMinutes() + " mins"); } if (duration.toMinutes() >= 60) { BigDecimal totalMins = new BigDecimal(duration.toMinutes()); BigDecimal minsInOneHour = new BigDecimal("60"); BigDecimal result = totalMins.divide(minsInOneHour, 2, RoundingMode.CEILING); if (result.doubleValue() % 1 == 0) { builder.append(result.intValue()); } else { builder.append(result); } builder.append(" hrs"); } return String.format("%s", builder); } }
The output of the above code is as follows:
2.07 hrs
In this code, the getDurationBetweenDates method calculates the duration between the start and end date-times using "Duration.between". It then constructs the duration string based on the duration value. The code checks if the duration is less than 60 minutes and appends it to the StringBuilder as minutes. If the duration is 60 minutes or more, it performs calculations to convert the duration to hours and minutes using BigDecimal for precise decimal calculations. The resulting duration is then appended to the StringBuilder as hours. Finally, the formatted duration string is returned from the getDurationBetweenDates method and printed in the main method.
This code allows you to find the duration between two dates in terms of hours and minutes, providing a convenient way to measure time intervals in your Java applications.