gurehbgui
gurehbgui

Reputation: 14694

android calendar timezones dont work?

i have a problem with the timezones of a android application.

in the following code is my example:

Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone("America/Miami"));
    c2 = Calendar.getInstance(TimeZone.getDefault());
    c2.set(2012, Calendar.MAY, 1, 9, 0, 0);

    tv2.setText(c1.getTime().toString());
    tv3.setText(c2.getTime().toString());

when i start the app and look at the textViews i find: enter image description here

why they are both gmt+2 and the first not the miami timezone?

Upvotes: 1

Views: 10801

Answers (2)

Priebe
Priebe

Reputation: 4992

I can duplicate what you're experiencing. You can get the correct time in Miami timezone by doing the following:

Calendar c1 = new GregorianCalendar(TimeZone.getTimeZone("GMT-4"));
int hour = c1.get(Calendar.HOUR);         
int minutes = c1.get(Calendar.MINUTE);     
int seconds = c1.get(Calendar.SECOND);

tv2.setText(String.format("%d:%d:%d", hour, minutes, seconds));

The output: 4:22:41

You can use either "America/New_York" or "GMT-4". However the last one as Chilledrat mention could have some issues with daylight saving.

Upvotes: 6

Shubhayu
Shubhayu

Reputation: 13562

Ok finally figured it out after a lot of trials. The problem that I observed is that, getTime() of Calendar seem to always return the date in the current TimeZone. I have still not found any data which says that this the way it works.

To get the data in the way you want, we need to introduce the SimpleDataFormat. this is what I did to get the data.

Calendar c1 = Calendar.getInstance(TimeZone.getTimeZone("America/New_York"), Locale.US);
Calendar c2 = Calendar.getInstance(TimeZone.getDefault());
c2.set(2012, Calendar.MAY, 1, 9, 0, 0);

SimpleDateFormat sdf = new SimpleDateFormat();
sdf.setCalendar(c1);
tv2.setText(sdf.format(c1.getTime()));
tv3.setText(c2.getTime().toString());

Here you get the output as per the defined TimeZone.

Note I also used the Locale as it is supposed to be a recommended practice. tell me if this works for you.

Upvotes: 6

Related Questions