Skip to content

How to calculate time difference using h format Java Netbeans

I am currently experimenting with a Self-Check in Airport Project.

What I would like to do is enter the Time of Departure using the format (hour)h(minute) Example(14h40)

I would have to validate this, by checking if the hour value is less than or equal to 23 and the minutes value is less than or equal to 59.

If this is valid then I would like to calculate the boarding time, which is 35 minutes before the departure time.

Any ideas?

The GUI I’m using.


It’s better to create a LocalTime and then every thing can be easy for you, to do this you can use :

String time = "14h40";
String[] hm = time.split("h");
LocalTime departureTime = null;
try {
    departureTime = LocalTime.of(Integer.valueOf(hm[0]), Integer.valueOf(hm[1]));
} catch (DateTimeException e) {
    // time is not correct, throw an exception!
    throw new IllegalArgumentException("Time is not correct");
// do calculation of the boarding time. 
LocalTime boardingTime = departureTime.minusMinutes(35);

Or as mentioned by Ole V.V. you can use a DateTimeFormatter:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("H'h'mm");
LocalTime departureTime = LocalTime.parse("4h40", formatter);