Using 2 Calendar class instances to get time difference

I am using the Calendar library within Java to try and figure out a problem with my application:

I have two Calendar instances, depart and arrive.

depart is leaving at 5:35 pm on 7/15/2015 from Chicago, while arrive is landing at 9:50 am on 7/16/15 in Berlin, Germany.

My current code to display the travel duration is:

    Calendar depart = Calendar.getInstance();       
    Calendar arrive = Calendar.getInstance();

    depart.setTimeZone(TimeZone.getTimeZone("America/Chicago"));
    arrive.setTimeZone(TimeZone.getTimeZone("Europe/Berlin"));

    depart.set(Calendar.MONTH, 6);
    depart.set(Calendar.DAY_OF_MONTH, 15);
    depart.set(Calendar.HOUR_OF_DAY, 17);
    depart.set(Calendar.MINUTE, 35);

    arrive.set(Calendar.MONTH, 6);
    arrive.set(Calendar.DAY_OF_MONTH, 16);
    arrive.set(Calendar.HOUR_OF_DAY, 9);
    arrive.set(Calendar.MINUTE, 50);

System.out.println("Depart: " + depart.getTime() + "\nArrive: " + arrive.getTime());

long hours = (arrive.getTimeInMillis() - depart.getTimeInMillis()) / (1000*60*60);
long minutes = (arrive.getTimeInMillis() - depart.getTimeInMillis()) / (1000*60) - (hours*60);

System.out.println("Flight duration: " + hours + " hours" + " " + minutes + " minutes");`

and the result is:

Depart: Wed Jul 15 17:35:53 CDT 2015 Arrive: Thu Jul 16 02:50:53 CDT 2015 Flight duration: 9 hours 15 minutes

...But I need the result to be:

Depart: Wed Jul 15 17:35:53 CDT 2015 Arrive: Thu Jul 16 **09:50:53 Central European Timezone** 2015 Flight duration: 9 hours 15 minutes

I need to change both depart and arrive so they display their local time, but still report the correct travel duration of 9 hours and 15 minutes.

Jon Skeet
people
quotationmark

You're calling getTime() to get a Date instance, and then calling toString() on that, implicitly - that will always use the system local time zone.

You want to use SimpleDateFormat so that you can control the time zone used for formatting. For example:

SimpleDateFormat formatter = new SimpleDateFormat("yyyy-MM-dd HH:mm z", Locale.US);
formatter.setTimeZone(depart.getTimeZone());
System.out.println("Depart: " + formatter.format(depart.getTime()));
formatter.setTimeZone(arrive.getTimeZone());
System.out.println("Arrive: " + formatter.format(arrive.getTime()));

people

See more on this question at Stackoverflow