java.time
I recommend you use the java.time
API to do it. The steps can be summarized in the following points:
- Create the instances of
LocalDateTime
using the current date at start time and the end time.
- If the
LocalDateTime
instance for end time is before the one for the start time, reset the instance for the end time to the midnight, then add one day to it and finally apply the time to it.
- Use
java.time.Duration
to get the duration between the instances of the LocalDateTime
.
Demo:
import java.time.Duration;
import java.time.LocalDate;
import java.time.LocalDateTime;
import java.time.LocalTime;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("Enter the start hour: ");
int startHour = scanner.nextInt();
System.out.print("Enter the start minute: ");
int startMinute = scanner.nextInt();
System.out.print("Enter the start hour: ");
int endHour = scanner.nextInt();
System.out.print("Enter the start minute: ");
int endMinute = scanner.nextInt();
LocalDate date = LocalDate.now();
LocalDateTime startDateTime = date.atTime(LocalTime.of(startHour, startMinute));
LocalDateTime endDateTime = date.atTime(LocalTime.of(endHour, endMinute));
if (startDateTime.isAfter(endDateTime)) {
endDateTime = endDateTime.with(LocalTime.MIN).plusDays(1).with(LocalTime.of(endHour, endMinute));
}
Duration duration = Duration.between(startDateTime, endDateTime);
System.out.println(duration);
// Custom format
// ####################################Java-8####################################
System.out.println(
"Total duration: " + String.format("%02d:%02d", duration.toHours(), duration.toMinutes() % 60));
// ##############################################################################
// ####################################Java-9####################################
System.out.println(
"Total duration: " + String.format("%02d:%02d", duration.toHoursPart(), duration.toMinutesPart()));
// ##############################################################################
}
}
A sample run:
Enter the start hour: 23
Enter the start minute: 45
Enter the start hour: 0
Enter the start minute: 45
PT1H
Total duration: 01:00
Total duration: 01:00
java.time.Duration
is modelled on ISO-8601 standards and was introduced with Java-8 as part of JSR-310 implementation. With Java-9 some more convenience methods were introduced.
Learn more about java.time API from Trail: Date Time.