java - Using 2 Calendar class instances to get time difference -


i using calendar library within java try , figure out problem application:

i have 2 calendar instances, depart , arrive.

depart leaving @ 5:35 pm on 7/15/2015 chicago, while arrive landing @ 9:50 on 7/16/15 in berlin, germany.

my current code display 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 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 need result 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 change both depart , arrive display local time, still report correct travel duration of 9 hours , 15 minutes.

you're calling gettime() date instance, , calling tostring() on that, implicitly - always use system local time zone.

you want use simpledateformat can control time zone used formatting. 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())); 

Comments

Popular posts from this blog

android - Gradle sync Error:Configuration with name 'default' not found -

java - Andrioid studio start fail: Fatal error initializing 'null' -

html - jQuery UI Sortable - Remove placeholder after item is dropped -