You may be after something like the following:
// Flying time for flight a
ZonedDateTime aDepartureTime = ZonedDateTime.of(
2021, 5, 1, 8, 0, 0, 0, ZoneId.of("Canada/Saskatchewan"));
Duration aFlyingTime = Duration.ofHours(7).plusMinutes(45);
ZonedDateTime aArrivalTime = aDepartureTime.plus(aFlyingTime)
.withZoneSameInstant(ZoneId.of("America/Buenos_Aires"));
// Flying time for flight b
ZonedDateTime bDepartureTime = ZonedDateTime.of(
2021, 5, 1, 18, 30, 0, 0, ZoneId.of("America/Buenos_Aires"));
if (aArrivalTime.isBefore(bDepartureTime)) {
System.out.format(
"Flight b can be reached since arrival time %s is before departure time %s%n",
aArrivalTime, bDepartureTime);
} else {
System.out.format(
"Flight b cannot be reached since arrival time %s is not before departure time %s%n",
aArrivalTime, bDepartureTime);
}
Output is:
Flight b cannot be reached since arrival time
2021-05-01T18:45-03:00[America/Buenos_Aires] is not before departure
time 2021-05-01T18:30-03:00[America/Buenos_Aires]
Use a ZonedDateTime
for a date and time in a time zone. Use a Duration
for — well, the class name says it.
Edit:
I am having trouble while adding all the Duration
s of a connected
flight, it adds up to 00:00 at the end. I use
Duration duration = Duration.ofHours(0);
duration.plus(flight.getDuration());
What might be off?
A common oversight. For the second statement you need
duration = duration.plus(flight.getDuration());
A Duration
, like virtually all java.time classes, is immutable. So the plus
method doesn’t add the other duration to the duration itself, but instead creates and returns a new Duration
object holding the sum of the two durations.
Also how can I get hh:MM version of Duration?
See the link at the bottom.
A LocalTime
is for a time of day. Don’t try to use it for a duration. A LocalDateTime
is a date and time of day without time zone or offset from UTC. Since you don’t know which time zone it is in, you cannot use it for calculations that involve conversion to another time zone. I know that LocalDateTime
is often used, but also very often in situations where it isn’t really the right class for the job. It hasn’t got very many good uses.
Links
How to format a duration in java? (e.g format H:MM:SS)