Java – total flight time between two time zones?
If we leave Frankfurt at 14:05 and arrive in Los Angeles at 16:40 How long does it take?
I've tried the following:
ZoneId frank = ZoneId.of("Europe/Berlin"); ZoneId los = ZoneId.of("America/Los_Angeles"); LocalDateTime dateTime = LocalDateTime.of(2015,02,20,14,05); LocalDateTime dateTime2 = LocalDateTime.of(2015,16,40); zoneddatetime berlinDateTime = zoneddatetime.of(dateTime,frank); zoneddatetime losDateTime2 = zoneddatetime.of(dateTime2,los); int offsetInSeconds = berlinDateTime.getOffset().getTotalSeconds(); int offsetInSeconds2 = losDateTime2.getOffset().getTotalSeconds(); Duration duration = Duration.ofSeconds(offsetInSeconds - offsetInSeconds2); System.out.println(duration);
But I can't get a successful answer in about 11 hours and 30 minutes Please help me solve the above problem Thank you:)
Solution
Getoffset is the wrong method The UTC offset of the area can be obtained at that time point It does not help to determine the actual time
One way is to use toinstant to explicitly get the instant. Instance represented by each value Then use duration Between to calculate the amount of time elapsed
Instant departingInstant = berlinDateTime.toInstant(); Instant arrivingInstant = losDateTime2.toInstant(); Duration duration = Duration.between(departingInstant,arrivingInstant);
Or, due to the duration. Com that works on the temporary object Between as well as instant and zoneddatetime all implement temporary. You can call duration directly on the zoneddatetime object between:
Duration duration = Duration.between(berlinDateTime,losDateTime2);
Finally, there is a shortcut to atao as mentioned above. If you want to get a unit directly, such as total seconds, you can Any of these are acceptable