Java Data Type How to - Get the flight departure and arrival time in different timezone








Question

We would like to know how to get the flight departure and arrival time in different timezone.

Answer

import java.time.LocalDateTime;
import java.time.LocalTime;
import java.time.Month;
import java.time.ZoneId;
import java.time.ZonedDateTime;
import java.time.format.DateTimeFormatter;
//from ww  w.j  a  v  a 2s .c om
public class Main {

  public static void main(String[] args) {
    LocalTime now = LocalTime.now();
    LocalTime currentTimeInLosAngeles = LocalTime.now(ZoneId
        .of("America/Los_Angeles"));
    System.out.println(String.format("now is %s and in LA is %s", now,
        currentTimeInLosAngeles));

    ZoneId leavingZone = ZoneId.of("Asia/Tel_Aviv");
    ZoneId arrivingZone = ZoneId.of("America/New_York");

    LocalDateTime leaving = LocalDateTime.of(2014, Month.JULY, 16, 23, 00);
    ZonedDateTime departure = ZonedDateTime.of(leaving, leavingZone);

    ZonedDateTime arrival = departure.withZoneSameInstant(arrivingZone)
        .plusHours(11).plusMinutes(51);

    DateTimeFormatter format = DateTimeFormatter.ofPattern("yyyy-MM-d  HH:mm");
    System.out
        .println(String.format("Departure: %s", departure.format(format)));
    System.out.println(String.format("Arrival: %s", arrival.format(format)));
  }
}

The code above generates the following result.