Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Total time of flight between two time zones?

If we leave Frankfurt at 14:05 and arrives in Los Angeles at 16:40. How long is the flight?

I tried the below :

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, 02, 20, 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 am not able to get the successful answer which is about 11hrs and 30min. Will some one please help me to figure out the problem above. Thanks you :)

like image 996
Uraz Pokharel Avatar asked Nov 28 '15 06:11

Uraz Pokharel


1 Answers

getOffset is the wrong method. That gets the UTC offset for that zone at that point in time. It doesn't help determine the actual time of day.

One way is to explicitly get the Instant represented by each value, using toInstant. 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);

Alternatively, since Duration.between works on Temporal objects, and both Instant and ZonedDateTime implement Temporal, you can just call Duration.between directly on the ZonedDateTime objects:

Duration duration = Duration.between(berlinDateTime, losDateTime2);

And lastly, there are shortcuts like the one atao mentioned that are fine if you want to get directly at a unit of measure such as total seconds. Any of these are acceptable.

like image 150
Matt Johnson-Pint Avatar answered Oct 04 '22 20:10

Matt Johnson-Pint