I have a flight itinerary program where I need to get difference between departure and arrival time. I get these specified times as String from the data. Here is my problem:
import static java.time.temporal.ChronoUnit.MINUTES; import java.time.LocalTime; import java.time.format.DateTimeFormatter; public class test2 { public static void main(String[] args) { DateTimeFormatter dateFormat = DateTimeFormatter.ofPattern("HHmm"); LocalTime departure = LocalTime.parse("1139", dateFormat); LocalTime arrival = LocalTime.parse("1435", dateFormat); LocalTime a = LocalTime.parse("0906", dateFormat); System.out.println(MINUTES.between(departure, arrival)); System.out.println(MINUTES.between(arrival, a)); } }
Output:
176 -329
The first time returns the difference between 11:39 and 14:35 just fine. But the second difference is only 5 hours while it should be 19 hours. How can I fix this, what am I doing wrong here?
Any help would be greatly appreciated.
EDIT: I am using graphs to store my data in. An example of a shortest route between two airports is like this:
Route for Edinburgh to Sydney 1 Edinburgh, 1139, TK3245, Istanbul, 1435 2 Istanbul, 0906, TK4557, Singapore, 1937 3 Singapore, 0804, QF1721, Sydney, 1521
These are the 3 flights that takes us from EDI to SYD. The format of the output above is (City, Departure Time, Flight No., Destination, Arrival Time).
Advertisement
Answer
The total number of minutes in 24 hours is 1440. So when the difference is below zero (but you need a positive one) then you should add a whole day to your result:
int diff = MINUTES.between(arrival, a); if (diff < 0) { diff += 1440; }
You can achieve the same thing using this:
int diff = (MINUTES.between(arrival, a) + 1440) % 1440;